Getting NSDictionary keys sorted by their respective values

Eric picture Eric · Mar 14, 2012 · Viewed 36.5k times · Source

I have an NSMutableDictionary with integer values, and I'd like to get an array of the keys, sorted ascending by their respective values. For example, with this dictionary:

mutableDict = {
    "A" = 2,
    "B" = 4,
    "C" = 3,
    "D" = 1,
}

I'd like to end up with the array ["D", "A", "C", "B"]. My real dictionary is much larger than just four items, of course.

Answer

Hermann Klecker picture Hermann Klecker · Mar 14, 2012

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