获取NSDictionary键按其各自的值排序

Eri*_*ric 42 cocoa-touch objective-c nsdictionary

我有一个NSMutableDictionary整数值,我想获得一个键的数组,按其各自的值升序排序.例如,使用这个字典:

mutableDict = {
    "A" = 2,
    "B" = 4,
    "C" = 3,
    "D" = 1,
}
Run Code Online (Sandbox Code Playgroud)

我想最终得到阵列["D", "A", "C", "B"].当然,我真正的字典比四个项目大得多.

Her*_*ker 66

NSDictionary方法keysSortedByValueUsingComparator:应该做的伎俩.

您只需要一个返回NSComparisonResult比较对象值的方法.

你的词典是

NSMutableDictionary * myDict;
Run Code Online (Sandbox Code Playgroud)

而你的数组是

NSArray *myArray;

myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedDescending;
     }
     if ([obj1 integerValue] < [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedAscending;
     }

     return (NSComparisonResult)NSOrderedSame;
}];
Run Code Online (Sandbox Code Playgroud)

只需使用NSNumber对象而不是数字常量.

顺便说一下,这取自:https: //developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

  • 理查德的建议比我的更优雅,因为NSNumber已经有了一个合适的比较功能,但我的可能更普遍. (4认同)

小智 27

NSDictionary有这个简洁的方法叫做allKeys.

如果你想要对数组进行排序,那么keysSortedByValueUsingComparator:应该这样做.

理查德的解决方案也可以使用,但可以进行一些您不一定需要的额外呼叫:

// Assuming myDictionary was previously populated with NSNumber values.
NSArray *orderedKeys = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
    return [obj1 compare:obj2];
}];
Run Code Online (Sandbox Code Playgroud)

  • 我相信你至少可以_try_使用这个方法(文档是链接的).如果您遇到问题,请回复您的编码尝试,我非常乐意为您提供帮助. (2认同)

Ric*_*III 14

这是一个解决方案:

NSDictionary *dictionary; // initialize dictionary
NSArray *sorted = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[dictionary objectForKey:obj1] compare:[dictionary objectForKey:obj2]];
}];
Run Code Online (Sandbox Code Playgroud)


Rud*_*vič 14

最简单的解决方案:

[dictionary keysSortedByValueUsingSelector:@selector(compare:)]