按NSNumber值对NSDictionary键进行排序

时间:2014-05-01 23:21:09

标签: ios objective-c sorting nsdictionary

我有一些像这样的NSDictionary:

@{
@"some key":{
    @"notImportantKey":@"asdasda",
    @"weight":@1
},
@"some key 2":{
    @"notImportantKey":@"asdasda",
    @"weight":@2
},
@"some key 3":{
    @"notImportantKey":@"asdasda",
    @"weight":@3
},
@"some key 4":{
    @"notImportantKey":@"asdasda",
    @"weight":@4
}}

我需要一组键(一些键,一些键2,......),按重量值排序。

2 个答案:

答案 0 :(得分:2)

这是keysSortedByValueUsingComparator:的用途。它比较字典中的值,并为您提供键使用这些值进行排序时的顺序。例如:

[yourDictionary keysSortedByValueUsingComparator:^(NSDictionary *a, NSDictionary *b) {
    return [a[@"weight"] compare:b[@"weight"]];
}];

答案 1 :(得分:2)

NSArray *keys = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary * obj2) {
    return [obj1[@"weight"] compare:obj2[@"weight"]];
}];

NSLog([keys description]);