Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 this dictionary:

mutableDict = {
    "A" = 2,
    "B" = 4,
    "C" = 3,
    "D" = 1,
}

I'd like to end up with the array ["D", "A", "C", "B"]. My real dictionary is much larger than just four items, of course.

question from:https://stackoverflow.com/questions/9708742/getting-nsdictionary-keys-sorted-by-their-respective-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...