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

后端 未结 5 820
臣服心动
臣服心动 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 14:58

    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.

提交回复
热议问题