对 nsdictionary 进行排序,它是如何工作的? [英] Sorting a nsdictionary, how does it work?
问题描述
我在理解这个 compare-using-selector
背后的逻辑时遇到了一些麻烦.
I'm having some trouble understanding the logic behind this compare-using-selector
thing.
我有以下代码,我正在尝试提取密钥并同时对它们进行排序.但是,它不排序.无论我做什么,输出 NSArray 的顺序都不会改变.
I have the following code, I'm trying extract the Keys and sorting them at the same time. But, it does not sort. The output NSArray's order never changes no matter what I do.
NSMutableDictionary *dictToSort = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Joe", [NSNumber numberWithInt:2], @"mark", [NSNumber numberWithInt:1], @"mdark", [NSNumber numberWithInt:3], nil];
NSArray *dictToSortKeys = [dictToSort keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"Not Sorted" );
NSNumber *xx = dictToSortKeys[0];
NSNumber *xy = dictToSortKeys[1];
NSNumber *xz = dictToSortKeys[2];
NSLog(@"Sorted %d %d %d", xx.integerValue , xy.integerValue, xz.integerValue);
我不明白这个 compare:
函数是如何工作的.它说它返回 NSOrderedAscending、NSOrderedSame 或 NSOrderedDescending
,但没有办法接收这些返回.而且,这应该神奇地工作吗?这个比较的文档很差.
I don't get how this compare:
function work. It says it returns NSOrderedAscending, NSOrderedSame or NSOrderedDescending
, but there is not way to receive these returns. And also, this is supposed to work magically? The documentation is quite poor for this comparison thing.
推荐答案
我认为您对 keysSortedByValueUsingSelector:
的作用感到困惑.它按值对字典条目进行排序,并按该顺序返回键.
I think you are confused about what keysSortedByValueUsingSelector:
does. It sorts the dictionary entries by value, and returns the keys in that order.
您的字典包含以下条目:
Your dictionary contains these entries:
Key Value
--- -----
1 mark
2 Joe
3 mdark
keysSortedByValueUsingSelector:
方法有效地按值"列对该表进行排序:
The keysSortedByValueUsingSelector:
method effectively sorts that table by the "Value" column:
Key Value
--- -----
2 Joe
1 mark
3 mdark
(注意Joe
在mark
之前,mark
在mdark
之前.)
(Note that Joe
is alphabetically before mark
and mark
is alphabetically before mdark
.)
然后它返回一个键数组,按照刚刚计算的顺序:@[@2,@1,@3]
.
Then it returns an array of the keys, in the order just computed: @[ @2, @1, @3 ]
.
请注意,keysSortedByValueUsingSelector:
从不比较键.它仅比较值.
Note that keysSortedByValueUsingSelector:
never compares the keys. It only compares the values.
如果你想按键本身对键数组进行排序,只需这样做:
If you want to sort the key array by the keys themselves, just do this:
NSArray *dictToSortKeys = [dictToSort.allKeys
sortedArrayUsingSelector:@selector(compare:)];
这篇关于对 nsdictionary 进行排序,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!