Sort NSDictionary keys by dictionary value in NSArray

I have seen many examples of sorting a dictionary by key and then getting the values, but how would I sort the values ​​instead.

eg.

{ blue:12; red:50; white:44; } 

I would like them to be sorted by a number descending to:

 { red:50; white:44; blue:12 } 

I tried to get a sorted nsarray of keys from which I could create an ordered nsarray, but the result still seems out of order.

  NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { if ( first < second ) { return (NSComparisonResult)NSOrderedAscending; } else if ( first > second ) { return (NSComparisonResult)NSOrderedDescending; } else { return (NSComparisonResult)NSOrderedSame; } }]; 
+7
source share
3 answers

Conceptually, NSDictionary is unsorted, as C0deH4cker has already said.

If you need an order, you can either write the keys to an array (but you may have problems saving the array after the key has been removed from the dictionary, but there are tutorials on how to create an un-keeping array using CFArray ) or NSSortedSet .

Or you can subclass NSDictionary - not very trivial, since NSDictionary is a cluster of classes. But, fortunately, Matt shows in his fantastic blogpost "OrderedDictionary: Subclassification of Cocoa Class Cluster" , how to use a little trick, relationship.


Please note that your code

  NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { if ( first < second ) { return (NSComparisonResult)NSOrderedAscending; } else if ( first > second ) { return (NSComparisonResult)NSOrderedDescending; } else { return (NSComparisonResult)NSOrderedSame; } }]; 

doesn't do what you want as you apply C-statements to objects. Now their pointers will be ordered.

it should be something like

  NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { return [first compare:second]; }]; 

or if you want to order scalars that are wrappers as objects (i.e. NSNumber)

  NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { if ([first integerValue] > [second integerValue]) return (NSComparisonResult)NSOrderedDescending; if ([first integerValue] < [second integerValue]) return (NSComparisonResult)NSOrderedAscending; return (NSComparisonResult)NSOrderedSame; }]; 
+9
source

Dictionaries are, by definition, disordered. They are accessed using hash tables for speed. The only way you can β€œorder” is to choose a different data type. The bast data type depends on your intentions.

0
source

Or you can just sort your NSString keys in the same way as:

 NSArray* sortedKeys = [sortedKeys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { NSNumber *A = @([obj1 LongValue]); NSNumber *B = @([obj2 LongValue]); return [A compare:B]; } ]; 
0
source

All Articles