Can i sort the NSDictionary on basis of key in Objective-C?

后端 未结 2 795
独厮守ぢ
独厮守ぢ 2020-11-27 16:17

Can I sort the NSDictionary on basis of key?

相关标签:
2条回答
  • 2020-11-27 16:24

    It is much simpler to use objectsForKeys:notFoundMarker: for that

    NSDictionary *yourDictionary;
    NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
    // As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
    NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];
    
    0 讨论(0)
  • 2020-11-27 16:48

    You can sort the keys and then create an NSMutableArray by iterating over them.

    NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
    NSMutableArray *sortedValues = [NSMutableArray array];
    for (NSString *key in sortedKeys)
        [sortedValues addObject: [dict objectForKey: key]];
    
    0 讨论(0)
提交回复
热议问题