Objective-C: Sort keys of NSDictionary based on dictionary entries

Viewed 22650

OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys]; Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString, then I want to sort keys based on the strings they correspond to. I think its some application of sortUsingComparator but its a little out of my reach at this point.

5 Answers

If any value from the dictionary is null then use this code

NSArray *keys = [typeDict allKeys];   
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedKeys = [keys sortedArrayUsingDescriptors:@[sd]];
NSLog(@"SORT 1 %@",sortedKeys);

NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
    id val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
    NSString *thekey = [sortedKeys objectAtIndex:counter];
    [sortedTypeDict setObject:val forKey:thekey];
    counter++;
}
NSLog(@"\n\nsorted dict: %@", sortedTypeDict);
Related