xcode 对 NSDictionary 进行降序排序。如何使用 `compare:options:` 选择器发送选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15825300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting an NSDictionary, descending. How do I send options with the `compare:options:` selector?
提问by ck_
I am attempting to sort an NSDictionary.
我正在尝试对 NSDictionary 进行排序。
From the Apple docsI see you can use keysSortedByValueUsingSelector
:
从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:)];
which gives:
这使:
// sortedKeysArray contains: Geography, History, Mathematics, English
but I want:
但我想要:
// sortedKeysArray contains: English, Mathematics, History, Geography
I have read that you can use compare:options:
, and an NSStringCompareOptions
to change the comparison to compare in the other direction.
我读过您可以使用compare:options:
, 和 anNSStringCompareOptions
来更改比较以在另一个方向进行比较。
However I don't understand how you send compare:options:
with an optionin the selector.
但是我不明白你如何在选择器中发送compare:options:
一个选项。
I want to do something like this:
我想做这样的事情:
NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:options:NSOrderDescending)];
How should I switch the order of the comparison?
我应该如何切换比较的顺序?
Related: https://discussions.apple.com/thread/3411089?start=0&tstart=0
相关:https: //discussions.apple.com/thread/3411089?start=0&tstart=0
回答by paulmelnikow
Option 1:Use a comparator to invoke -compare:
in reverse: (Thanks Dan Shelly!)
选项 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];
}];
Just reverse the descending and ascending return statements and you should get just what you want.
只需颠倒降序和升序的返回语句,你就会得到你想要的。
Option 2:Reverse the array you have:
选项 2:反转您拥有的数组:
回答by YvesLeBorg
I use :
我用 :
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
self. sortedKeys = [[self.keyedInventoryItems allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortOrder]];