Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keysSortedByValueUsingComparator not giving a properly ordered array

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?

like image 851
Andrew Lauer Barinov Avatar asked Oct 02 '12 01:10

Andrew Lauer Barinov


1 Answers

Perhaps you're misunderstanding what the keysSortedByValue:... method does. It does not sort the keys (for that you would just sort the array returned by allKeys), instead it sorts the values and then applies their order to the keys.

So let's say you have the following dictionary:

{"Orange": 1, "Apple": 3, "Peach": 2}

The result would be:

"Orange", "Peach", "Apple"

because that corresponds to the sorted order of the values (1, 2, 3).

like image 133
omz Avatar answered Oct 16 '22 23:10

omz