ios – 对NSDictionary进行排序,降序.如何使用`compare:options:`选择器发送选项?

我试图对NSDictionary进行排序.

Apple docs我看到你可以使用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:)];

这使:

// sortedKeysArray contains: Geography,History,Mathematics,English

但我想要:

// sortedKeysArray contains: English,Geography

我已经读过你可以使用compare:options:和NsstringCompareOptions来改变比较以便在另一个方向上进行比较.

但是我不明白你如何发送compare:options:在选择器中有一个选项.

我想做这样的事情:

NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:options:NSOrderDescending)];

我应该如何切换比较的顺序?

有关:
https://discussions.apple.com/thread/3411089?start=0&tstart=0

解决方法

选项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];
}];

只需反转降序和升序返回语句,你应该得到你想要的.

选项2:反转您拥有的阵列:

How can I reverse a NSArray in Objective-C?

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...