Sorting a nsdictionary, how does it work?

可紊 提交于 2019-12-25 06:07:26

问题


I'm having some trouble understanding the logic behind this compare-using-selector thing.

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);

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.


回答1:


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

The keysSortedByValueUsingSelector: method effectively sorts that table by the “Value” column:

Key Value
--- -----
 2  Joe
 1  mark
 3  mdark

(Note that Joe is alphabetically before mark and mark is alphabetically before mdark.)

Then it returns an array of the keys, in the order just computed: @[ @2, @1, @3 ].

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:)];


来源:https://stackoverflow.com/questions/17257582/sorting-a-nsdictionary-how-does-it-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!