Getting NSDictionary keys sorted by their respective values

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

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 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!