Getting NSDictionary keys sorted by their respective values

前端 未结 5 857
广开言路
广开言路 2020-11-27 14:59

I have an NSMutableDictionary with integer values, and I\'d like to get an array of the keys, sorted ascending by their respective values. For example, with thi

5条回答
  •  借酒劲吻你
    2020-11-27 15:42

    Here's a solution:

    NSDictionary *dictionary; // initialize dictionary
    NSArray *sorted = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [[dictionary objectForKey:obj1] compare:[dictionary objectForKey:obj2]];
    }];
    

提交回复
热议问题