获取按各自的值sorting的NSDictionary键

我有一个NSMutableDictionary与整数值,我想获得一个按键排列,按照各自的值升序排列。 例如,用这个字典:

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

我想结束数组["D", "A", "C", "B"] 。 当然,我真正的字典比四件物品要大得多。

NSDictionary方法keysSortedByValueUsingComparator:应该做的伎俩。

您只需要一个返回NSComparisonResult的方法来比较对象的值。

你的字典是

 NSMutableDictionary * myDict; 

而你的数组是

 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; }]; 

只需使用NSNumber对象而不是数字常量。

顺便说一句,这是取自: https : //developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

NSDictionary有这个整洁的方法称为allKeys

如果你想要数组sorting虽然, keysSortedByValueUsingComparator:应该做的伎俩。

理查德的解决scheme也可以,但是可以做一些你不一定需要的额外的电话:

 // Assuming myDictionary was previously populated with NSNumber values. NSArray *orderedKeys = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){ return [obj1 compare:obj2]; }]; 

这是一个解决scheme:

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

最简单的解决scheme:

[dictionary keysSortedByValueUsingSelector:@selector(compare:)]

在这里我做了这样的事情:

 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 < [weekDays count]; i++) { dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],@"WeekDay",[weekDays objectAtIndex:i],@"Name",nil]; [dictArray addObject:dict]; } NSLog(@"Before Sorting : %@",dictArray); @try { //for using NSSortDescriptor NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"WeekDay" ascending:YES]; NSArray *descriptor = @[sortDescriptor]; NSArray *sortedArray = [dictArray sortedArrayUsingDescriptors:descriptor]; NSLog(@"After Sorting : %@",sortedArray); //for using predicate //here i want to sort the value against weekday but only for WeekDay<=5 int count=5; NSPredicate *Predicate = [NSPredicate predicateWithFormat:@"WeekDay <=%d",count]; NSArray *results = [dictArray filteredArrayUsingPredicate:Predicate]; NSLog(@"After Sorting using predicate : %@",results); } @catch (NSException *exception) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorting cant be done because of some error" message:[NSString stringWithFormat:@"%@",exception] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert setTag:500]; [alert show]; [alert release]; }