sort NSDictionary values by key alphabetical order

后端 未结 4 1906
谎友^
谎友^ 2020-12-14 01:51

I can get an array of dictionary keys sorted by values, but how to I get an array of values sorted by dictionary keys? I\'ve been looking everywhere with no luck. Any help a

相关标签:
4条回答
  • 2020-12-14 02:08

    I created a category on NSDictionary to get this accomplished:

    @implementation NSDictionary (Extra)
    
    -(NSArray *) sortedKeys {
        return [[self allKeys] sortedArrayUsingSelector:@selector(compare:)];
    }
    
    -(NSArray *) allValuesSortedByKey {
        return [self objectsForKeys:self.sortedKeys notFoundMarker:[NSNull null]];
    }
    
    -(id) firstKey {
        return [self.sortedKeys firstObject];
    }
    
    -(id) firstValue {
        return [self valueForKey: [self firstKey]];
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-14 02:15

    This might work:

    NSArray * sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
    
    NSArray * objects = [dict objectsForKeys: sortedKeys notFoundMarker: [NSNull null]];
    

    or in Swift

    let objects = dict.keys.sorted().flatMap{ dict[$0] }
    

    or

    let objects = dict.sorted{ $0.0 < $1.0 }.map{ $1 }
    

    …and that is why you should start developing in Swift

    0 讨论(0)
  • 2020-12-14 02:22

    One way is to construct the array of sorted dictionary keys, then create another array of the values based on the array of keys:

    //Construct array of sorted keys
    NSArray keyarray = ... //etc
    
    NSMutableArray valuearray = [[NSMutableArray alloc] init];
    for (id key in keyarray) {
        [valuearray addObject:[dict objectForKey:key]];
    }
    
    0 讨论(0)
  • 2020-12-14 02:25

    My experience shows that sorting NSDictionary by keys is not much useful. Although after logging the NSDictionary they seem to be sorted, when needed to put them in a tableview they are not in order any more.

    I suggest storing the keys in an NSArray property and then query the NSDictionary objects according to the order of the keys in the NSArray.

    0 讨论(0)
提交回复
热议问题