按照字典里某个键的值对NSArray中的字典进行排序

68
我有一个由字典填充的数组,我需要按照其中一个键的值的字母顺序对该数组进行排序。
这是我的数组:
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键进行排序?


1
这种排序也被称为Schwartzian Transform。我已经为此制作了一个Swift包:https://github.com/neoneye/SwiftySchwartzianTransform - neoneye
11个回答

113

我认为这样做就可以了:

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

我从Sort Descriptor Programming Topics获取了代码。此外,sortedArrayUsingDescriptors:方法将会对myArray的每个元素发送一个valueForKey:消息,并使用标准比较器来对返回值进行排序,因此也涉及到了键值编码的知识。


如何在Swift2中使用这个? - user3622576

9
我们通过以下方法解决了问题。
[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];

说明:

jsonData - 可变数组,用于存储解析后的JSON数据。

fullname - 我们想要排序的数据项。

id - 一组内部字典中带有的唯一数据。


5
作为QED代码的补充,
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];

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


4

在Swift中:

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

4
使用以下代码按字典中“brand”键排序:
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

如果你想按照字典中的两个键排序,比如“brand”键和“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);

4
 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;
        }];

虽然使用sortedArrayUsingComparator是正确的方法,但是调用"valueForKey"最多四次而不是两次"objectForKey"是不好的。顺便说一下,由于你期望使用字典,所以应该使用NSDictionary*作为类型,而不是id。 - gnasher729

2

在使用NSSortDescriptor过程中,我的代码经常崩溃。后来我使用了一个块,在我的用例中非常有效,其中我期望“排名”是一个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;
}];

1

只需尝试最简单的方法...

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];

1
你可以做到这一点。
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]];

1
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接