获取NSDictionary键按其各自的值排序

时间:2012-03-14 19:23:32

标签: objective-c cocoa-touch nsdictionary

我有一个带有整数值的NSMutableDictionary,我想得到一个按键数组,按各自的值递增排序。例如,使用此词典:

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

我想结束数组["D", "A", "C", "B"]。当然,我真正的字典比四个项目大得多。

5 个答案:

答案 0 :(得分:66)

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个对象而不是数字常量。

BTW,这取自: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

答案 1 :(得分:27)

NSDictionary有一个名为allKeys的简洁方法。

如果您希望对数组进行排序,keysSortedByValueUsingComparator:应该可以解决问题。

理查德的解决方案也有效,但会做一些你不一定需要的额外电话:

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

答案 2 :(得分:14)

这是一个解决方案:

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

答案 3 :(得分:14)

最简单的解决方案:

[dictionary keysSortedByValueUsingSelector:@selector(compare:)]

答案 4 :(得分:2)

我在这里做了类似的事情:

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