按字母顺序对NSMutableDictionary的值进行排序

时间:2014-03-24 07:11:55

标签: ios objective-c nsmutabledictionary

我有NSMutableDictionary,其中Integers为Key,NSString为Values,例如:

键 - 值

1 - B

2 - C

3 - A

现在我想使用值按字母顺序对NSMutableDictionary进行排序。所以我希望我的字典如下:Key(3,1,2) - > Value(A,B,C)。我该怎么做?

2 个答案:

答案 0 :(得分:3)

来自Apple文档: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html#//apple_ref/doc/uid/20000134-SW4

按值排序字典键:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:63], @"Mathematics",
    [NSNumber numberWithInt:72], @"English",
    [NSNumber numberWithInt:55], @"History",
    [NSNumber numberWithInt:49], @"Geography",
    nil];

NSArray *sortedKeysArray =
    [dict keysSortedByValueUsingSelector:@selector(compare:)];
// sortedKeysArray contains: Geography, History, Mathematics, English

阻止自定义词典排序:

NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {
          return (NSComparisonResult)NSOrderedDescending;
     }

     if ([obj1 integerValue] < [obj2 integerValue]) {
          return (NSComparisonResult)NSOrderedAscending;
     }
     return (NSComparisonResult)NSOrderedSame;
}];

答案 1 :(得分:2)

尝试这个逻辑

  NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"B",@"B",@"A",@"A",@"C",@"C", nil];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:[dict allKeys]];
    [sortedArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *key in sortedArray) {
        NSLog(@"%@",[dict objectForKey:key]);
    }