按字典中键的值对字典的 NSArray 进行排序 [英] Sorting NSArray of dictionaries by value of a key in the dictionaries

查看:34
本文介绍了按字典中键的值对字典的 NSArray 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由字典填充的数组,我需要按字典的其中一个键的值按字母顺序对数组进行排序.

I have an array populated by dictionaries, and I need to sort the array alphabetically by the values of one of the keys of the dictionaries.

这是我的数组:

tu dictus: (
    {
    brand = Ryul;
    productTitle = Any;
    quantity = 1;
    subBrand = "Ryul INJ";
    type = Product;
},
    {
    brand = Trol;
    productTitle = Different;
    quantity = 2;
    subBrand = "";
    type = Brand;
},
    {
    brand = Dtor;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
},
    {
    brand = Ryul;
    productTitle = Different;
    quantity = 2;
    subBrand = "Ryul CHES";
    type = SubBrand;
},
    {
    brand = Anan;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
}
)

通常用于排序数组我会使用

Normally for sorting an array I will use

myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

但是如何使用字典的brand键进行排序?

But how do sort using the brand key of the dictionary?

推荐答案

我认为这样做可以:

brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

我从 排序描述符编程主题.此外,键值编码开始发挥作用,在sortedArrayUsingDescriptors: 会向 myArray 中的每个元素发送一个 valueForKey:,然后使用标准比较器对返回值进行排序.

I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Coding comes into play, in that sortedArrayUsingDescriptors: will send a valueForKey: to each element in myArray, and then use standard comparators to sort the returned values.

这篇关于按字典中键的值对字典的 NSArray 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆