Getting NSDictionary keys sorted by their respective values

The NSDictionary Method keysSortedByValueUsingComparator: should do the trick.

You just need a method returning an NSComparisonResult that compares the object’s values.

Your Dictionary is

NSMutableDictionary * myDict;

And your Array is

NSArray *myArray;

myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedDescending;
     }
     if ([obj1 integerValue] < [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedAscending;
     }

     return (NSComparisonResult)NSOrderedSame;
}];

Just use NSNumber objects instead of numeric constants.

BTW, this is taken from:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

Leave a Comment