Getting NSDictionary keys sorted by their respective values

前端 未结 5 860
广开言路
广开言路 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:24

    The NSDictionary Method keysSortedByValueUsingComparator: should do the trick.

    You just need a method returning an NSComparisonResult that compares the object's values.

    Your Dictionary is

    NSMutableDictionary * myDict;
    

    And your Array is

    NSArray *myArray;
    
    myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
    
         if ([obj1 integerValue] > [obj2 integerValue]) {
    
              return (NSComparisonResult)NSOrderedDescending;
         }
         if ([obj1 integerValue] < [obj2 integerValue]) {
    
              return (NSComparisonResult)NSOrderedAscending;
         }
    
         return (NSComparisonResult)NSOrderedSame;
    }];
    

    Just use NSNumber objects instead of numeric constants.

    BTW, this is taken from: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

提交回复
热议问题