可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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]
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
回答2:
NSDictionary has this neat method called allKeys
.
If you want the array to be sorted though, keysSortedByValueUsingComparator:
should do the trick.
Richard's solution also works but makes some extra calls you don't necessarily need:
// Assuming myDictionary was previously populated with NSNumber values. NSArray *orderedKeys = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){ return [obj1 compare:obj2]; }];
回答3:
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]]; }];
回答4:
The simplest solution:
[dictionary keysSortedByValueUsingSelector:@selector(compare:)]
回答5:
Here i have done something like this:
NSMutableArray * weekDays = [[NSMutableArray alloc] initWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday", nil]; NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; NSMutableArray *dictArray = [[NSMutableArray alloc] init]; for(int i = 0; i