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

Sort keys of NSDictionary based on dictionary keys

Abobe is for returning a sorted array with based on dictionary content, this is for returning an array sorted by dictionary key:

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    return [a compare:b];
}];
NSMutableArray *sortedValues = [NSMutableArray new];
for(NSString *key in sortedKeys)
    [sortedValues addObject:[dictFilterValues objectForKey:key]];

NSDictionary *dict = // however you obtain the dictionary
NSMutableArray *sortedKeys = [NSMutableArray array];

NSArray *objs = [dict allValues];
NSArray *sortedObjs = [objs sortedArrayUsingSelector:@selector(compare:)];
for (NSString *s in sortedObjs)
    [sortedKeys addObjectsFromArray:[dict allKeysForObject:s]];

Now sortedKey will contain the keys sorted by their corresponding objects.


NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSString *first = [someDictionary objectForKey:a];
    NSString *second = [someDictionary objectForKey:b];
    return [first compare:second];
}];