按字典中键的值对字典的NSArray进行排序

man*_*urt 62 sorting objective-c nsdictionary nsarray ios

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

这是我的阵列:

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;
}
)
Run Code Online (Sandbox Code Playgroud)

通常用于排序我将使用的数组

myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)

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

QED*_*QED 111

我想这会做到:

brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
Run Code Online (Sandbox Code Playgroud)

我从Sort Descriptor Programming Topics中提取代码.此外,键值编码开始起作用,其中sortedArrayUsingDescriptors:将向valueForKey:每个元素发送一个myArray,然后使用标准比较器对返回的值进行排序.


Pra*_*jan 9

我们通过使用方法得到了解决方案

[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
Run Code Online (Sandbox Code Playgroud)

哪里:-

jsonData - MutableArray,其中包含解析的JSON数据.

fullname - 我们要排序的数据.

id - 内部字典附带的唯一数据.


myl*_*gon 5

作为 QED 代码的补充,

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];
Run Code Online (Sandbox Code Playgroud)

这澄清了变量的类别并通过快速枚举优化了数组创建。谢谢