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

前端之家收集整理的这篇文章主要介绍了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?

原文链接:https://www.f2er.com/iOS/333031.html

猜你在找的iOS相关文章