cks*_*ubs 7 xcode cocoa objective-c ios
我试图对NSDictionary进行排序.
从Apple文档 我看到你可以使用keysSortedByValueUsingSelector:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:63], @"Mathematics",
[NSNumber numberWithInt:72], @"English",
[NSNumber numberWithInt:55], @"History",
[NSNumber numberWithInt:49], @"Geography",
nil];
NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)
这使:
// sortedKeysArray contains: Geography, History, Mathematics, English
Run Code Online (Sandbox Code Playgroud)
但我想要:
// sortedKeysArray contains: English, Mathematics, History, Geography
Run Code Online (Sandbox Code Playgroud)
我已经读过你可以使用compare:options:,并且NSStringCompareOptions可以改变比较以便在另一个方向上进行比较.
但是我不明白你如何compare:options: 使用选择器中的选项发送.
我想做这样的事情:
NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:options:NSOrderDescending)];
Run Code Online (Sandbox Code Playgroud)
我该如何切换比较的顺序?
相关:https: //discussions.apple.com/thread/3411089?start = 0&tstart = 0
pau*_*kow 13
选项1:使用比较器-compare:反向调用:(感谢Dan Shelly!)
NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
// Switching the order of the operands reverses the sort direction
return [objc2 compare:obj1];
}];
Run Code Online (Sandbox Code Playgroud)
只需反转降序和升序返回语句,您应该得到您想要的.
选项2:反转您拥有的阵列:
我用 :
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
self. sortedKeys = [[self.keyedInventoryItems allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortOrder]];
Run Code Online (Sandbox Code Playgroud)