KeysSortedByValueUsingComparator does not give a properly ordered array

I have a dictionary whose keys consist of NSNumber s. I use keysSortedByValueUsingComparator as follows:

 NSArray *sortedKeys = [self.platformDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [(NSNumber*)obj2 compare:(NSNumber*)obj1]; }]; 

However, here is the result:

 (lldb) po sortedKeys (NSArray *) $1 = 0x0704bd20 <__NSArrayI 0x704bd20>( 100000, 250000, 1000000, 500000, 3000000, 2000000, 5000000, 10000000 ) 

What does not work. Is this a mistake in the method implementation or is there another problem here?

+4
source share
3 answers

You may not understand what the keysSortedByValue:... method keysSortedByValue:... . It does not sort the keys (for this you just sorted 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} 

Result:

 "Orange", "Peach", "Apple" 

since this corresponds to the sorted order of values ​​(1, 2, 3).

+8
source

You can simply use sortedArrayUsingSelector:

 NSArray *sortedArray = [[self.PlatformDict allKeys] sortedArrayUsingSelector:@selector(compare:)] 
+4
source

Replace the inside of the unit with the following. This will tell you if this is a problem with the comparison method or something else.

  if ([obj1 integerValue] > [obj2 integerValue]) { return (NSComparisonResult)NSOrderedDescending; } if ([obj1 integerValue] < [obj2 integerValue]) { return (NSComparisonResult)NSOrderedAscending; } return (NSComparisonResult)NSOrderedSame; 
+1
source

Source: https://habr.com/ru/post/1437310/


All Articles