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

后端 未结 5 832
臣服心动
臣服心动 2021-02-13 14:30

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 corre

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 15:16

    Just write it here cause I didn't find it anywhere: To get an alphanumeric sorted NSDictionary back from an NSDictionary based on the value - which in my case was neccessary - you can do the following:

    //sort typeDict alphanumeric to show it in order of values
        NSArray *keys = [typeDict allKeys];
    
        NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSString *first = [typeDict objectForKey:a];
            NSString *second = [typeDict objectForKey:b];
            return [first compare:second];
        }];
        NSLog(@"sorted Array: %@", sortedKeys);
    
        NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
        int counter = 0;
        for(int i=0; i < [typeDict count]; i++){
            NSString *val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
            NSString *thekey = [sortedKeys objectAtIndex:counter];
            [sortedTypeDict setObject:val forKey:thekey];
            counter++;
        }
        NSLog(@"\n\nsorted dict: %@", sortedTypeDict);
    

    Not a big deal!

提交回复
热议问题