Sort an NSMutableDictionary Sort an NSMutableDictionary ios ios

Sort an NSMutableDictionary


Get the Array of the Values, sort that array and then get the key corresponding to the value.

You can get the values with:

NSArray* values = [myDict allValues];NSArray* sortedValues = [values sortedArrayUsingSelector:@selector(comparator)];

But, if the collection is as you show in your example, (I mean, you can infer the value from the key), you can always sort the keys instead messing with the values.

Using:

NSArray* sortedKeys = [myDict keysSortedByValueUsingSelector:@selector(comparator)];

The comparator is a message selector which is sent to the object you want to order.

If you want to order strings, then you should use a NSString comparator.The NSString comparators are i.e.: caseInsensitiveCompare or localizedCaseInsensitiveCompare:.

If none of these are valid for you, you can call your own comparator function

[values sortedArrayUsingFunction:comparatorFunction context:nil]

Being comparatorFunction (from AppleDocumentation)

NSInteger intSort(id num1, id num2, void *context){    int v1 = [num1 intValue];    int v2 = [num2 intValue];    if (v1 < v2)        return NSOrderedAscending;    else if (v1 > v2)        return NSOrderedDescending;    else        return NSOrderedSame;}


The simplest way is:

NSArray *sortedValues = [[yourDictionary allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];for(NSString *valor in sortedValues){    for(NSString *clave in [yourDictionary allKeys]){        if ([valor isEqualToString:[yourDictionary valueForKey:clave]]) {            [orderedDictionary setValue:valor forKey:clave];        }    }}


Use this method:

- (NSArray *)sortKeysByIntValue:(NSDictionary *)dictionary {  NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {      int v1 = [obj1 intValue];      int v2 = [obj2 intValue];      if (v1 < v2)          return NSOrderedAscending;      else if (v1 > v2)          return NSOrderedDescending;      else          return NSOrderedSame;  }];  return sortedKeys;}

Call it and then create a new dictionary with keys sorted by value:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:                           @"4", @"dog",                           @"3", @"cat",                           @"6", @"turtle",                            nil];NSArray *sortedKeys = [self sortKeysByIntValue:dictionary];NSMutableDictionary *sortedDictionary = [[NSMutableDictionary alloc] init];for (NSString *key in sortedKeys){    [sortedDictionary setObject:dictionary[key] forKey:key];}