I have a dictionary whose keys consist of NSNumbers. I am using keysSortedByValueUsingComparator as follows:
NSArray *sortedKeys = [self.platformDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSNumber*)obj2 compare:(NSNumber*)obj1];
}];
However here is the result I get:
(lldb) po sortedKeys
(NSArray *) $1 = 0x0704bd20 <__NSArrayI 0x704bd20>(
100000,
250000,
1000000,
500000,
3000000,
2000000,
5000000,
10000000
)
Which is out of order. Is this a bug with the method implementation or is there another issue here?
Perhaps you’re misunderstanding what the
keysSortedByValue:...method does. It does not sort the keys (for that you would just sort the array returned byallKeys), instead it sorts the values and then applies their order to the keys.So let’s say you have the following dictionary:
The result would be:
because that corresponds to the sorted order of the values (1, 2, 3).