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
小智 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)
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)