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

后端 未结 5 830
臣服心动
臣服心动 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:08

    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);
    

提交回复
热议问题