繁体   English   中英

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

[英]Sorting NSArray of dictionaries by value of a key in 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;
}
)

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

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

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

我想这会做到:

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

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

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

[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];

哪里:-

jsonData - 包含解析的JSON数据的MutableArray。

fullname - 我们要排序的数据。

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

 arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if ([[obj1 valueForKey:@"iUserId"] integerValue] > [[obj2 valueForKey:@"iUserId"] integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            if ([[obj1 valueForKey:@"iUserId"] integerValue] < [[obj2 valueForKey:@"iUserId"] integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        }];

在switf中:

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "brand", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])

使用以下代码使用字典中的“品牌”键进行排序。

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

使用以下代码,如果要根据字典中的两个键进行排序; 比如,“品牌”键和productTitle键来自字典: -

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productTitle" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
NSArray * sortedArray = [feedData sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

作为QED代码的补充,

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

这澄清了变量的类,并使用快速枚举优化了数组创建。 谢谢

当我使用NSSortDescriptor时,我的代码崩溃了,所以最终使用了一个在我的用例中运行良好的块,我希望“rank”是一个NSNumber。 如果对象无法转换为整数,则不会对其进行排序,但也不会导致崩溃。

NSArray *sortedArray = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    long data1 = [[obj1 valueForKey:@"rank"] integerValue];
    long data2 = [[obj2 valueForKey:@"rank"] integerValue];
    if (data1 > data2) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if (data1 < data2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

试试最简单的方法......

myArray = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
[tempArray addObjectsFromArray: myArray];

NSString *key = @"brand";
NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
[brandDescriptor release];
[tempArray removeAllObjects];
tempArray = (NSMutableArray*)sortedArray;
[myArray removeAllObjects];
[myArray addObjectsFromArray:tempArray];

你可以这样做 。

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d LLLL yyyy"];

NSComparator compareDates = ^(id string1, id string2)
{
    NSDate *date1 = [formatter dateFromString:string1];
    NSDate *date2 = [formatter dateFromString:string2];

    return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO comparator:compareDates];
[array sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];
NSSortDescriptor *brandDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Position" ascending:YES selector:@selector(localizedStandardCompare:)] autorelease];
      NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
      NSArray  *sortedArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors];
     array_PreLagData=(NSMutableArray*)sortedArray;

unsorted array
Printing description of arrTemp:
<__NSArrayM 0x10282100>(
{
    Milker2 = "11:03:17 AM";
    Position = 2;
},
{
    Milker1 = "11:03:28 AM";
    Position = 25;
},
{
    Milker3 = "11:03:18 AM";
    Position = 3;
},
{
    Milker1 = "11:03:16 AM";
    Position = 1;
    Strip = "11:32:32 AM";
},
{
    Milker1 = "11:03:21 AM";
    Position = 10;
}
)
Sorted array
<__NSArrayI 0x101363c0>(
{
    Milker1 = "11:03:16 AM";
    Position = 1;
    Strip = "11:32:32 AM";
},
{
    Milker2 = "11:03:17 AM";
    Position = 2;
},
{
    Milker3 = "11:03:18 AM";
    Position = 3;
},
{
    Milker1 = "11:03:21 AM";
    Position = 10;
},
{
    Milker1 = "11:03:28 AM";
    Position = 25;
}
)

[enter link description here][1]


  [1]: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE

用于swift 4

let sortedArray = arrayTobeSort.sorted {$0["keyName"].compare($1["keyName"]) == ComparisonResult.orderedAscending}

您还可以使用ComparisonResult.orderedDescending按降序排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM