【问题标题】:Sort an NSMutableDictionary对 NSMutableDictionary 进行排序
【发布时间】:2011-06-01 07:31:07
【问题描述】:

我有一个NSMutableDictionaryNSString 映射到NSString(虽然值是NSStrings,但它们实际上只是整数)。

例如考虑以下映射,

"dog" --> "4"
"cat" --> "3"
"turtle" --> "6"

我希望字典中的前 10 个条目按值的降序排序。有人可以给我看这个代码吗?也许有一个键数组和另一个值数组。不管怎样,我不介意。我只是想让它高效。

谢谢!

【问题讨论】:

    标签: ios dictionary nsmutabledictionary


    【解决方案1】:

    获取值的数组,对该数组进行排序,然后获取与该值对应的键。

    您可以通过以下方式获取值:

    NSArray* values = [myDict allValues];
    NSArray* sortedValues = [values sortedArrayUsingSelector:@selector(comparator)];
    

    但是,如果集合如您在示例中显示的那样(我的意思是,您可以从键中推断出值),您始终可以对键进行排序,而不是弄乱值。

    使用:

    NSArray* sortedKeys = [myDict keysSortedByValueUsingSelector:@selector(comparator)];
    

    比较器是一个消息选择器,它被发送到您要订购的对象。

    如果你想对字符串排序,那么你应该使用 NSString 比较器。 NSString 比较器是:caseInsensitiveCompare 或localizedCaseInsensitiveCompare:。

    如果这些都不适合你,你可以调用你自己的比较器函数

    [values sortedArrayUsingFunction:comparatorFunction context:nil]
    

    作为comparatorFunction(来自AppleDocumentation

    NSInteger intSort(id num1, id num2, void *context)
    {
        int v1 = [num1 intValue];
        int v2 = [num2 intValue];
        if (v1 < v2)
            return NSOrderedAscending;
        else if (v1 > v2)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
    

    【讨论】:

    • 好的,假设我想使用您的第二种方法。究竟什么是“比较器”。对不起,我以前从未使用过这种方法。这是否意味着我需要编写自己的函数?它会是什么样子?谢谢!!
    • @HyLian 如果 NSDictionary 包含不同键的重复值怎么办。您将如何跟踪应该拿起哪个钥匙?
    • Sorting a Dictionary 在 Apple 的 Collections Programming Guide 中提供了有关此主题的更多信息。
    【解决方案2】:

    最简单的方法是:

    NSArray *sortedValues = [[yourDictionary allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];
    for(NSString *valor in sortedValues){
        for(NSString *clave in [yourDictionary allKeys]){
            if ([valor isEqualToString:[yourDictionary valueForKey:clave]]) {
                [orderedDictionary setValue:valor forKey:clave];
            }
        }
    }
    

    【讨论】:

    • 这效率不高,接受的答案有正确的解决方案。
    【解决方案3】:

    使用这个方法:

    - (NSArray *)sortKeysByIntValue:(NSDictionary *)dictionary {
    
      NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
          int v1 = [obj1 intValue];
          int v2 = [obj2 intValue];
          if (v1 < v2)
              return NSOrderedAscending;
          else if (v1 > v2)
              return NSOrderedDescending;
          else
              return NSOrderedSame;
      }];
      return sortedKeys;
    }
    

    调用它,然后使用按值排序的键创建一个新字典:

    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                               @"4", @"dog",
                               @"3", @"cat",
                               @"6", @"turtle", 
                               nil];
    
    NSArray *sortedKeys = [self sortKeysByIntValue:dictionary];
    NSMutableDictionary *sortedDictionary = [[NSMutableDictionary alloc] init];
    
    for (NSString *key in sortedKeys){
        [sortedDictionary setObject:dictionary[key] forKey:key];
    }
    

    【讨论】:

      【解决方案4】:

      对键进行排序并使用它来填充具有值的数组:

      NSArray *keys = [dict allKeys];
      NSArray *sKeys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
      NSMutableArray *sValues = [[[NSMutableArray alloc] init] autorelease];
      
      for(id k in sKeys) {
          id val = [dict objectForKey:k];
          [sValues addObject:val];
      }
      

      【讨论】:

      • 非常适合将字典转换为其等效的排序数组,按键排序。
      • 不是对两位数进行排序。
      【解决方案5】:
      NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
      [unsortedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
      recentSortedArray = [stories copy];
      

      【讨论】:

        【解决方案6】:

        如果您想对此类示例的键“名称”按升序对数据进行排序,那么这可能会对您有所帮助。

        arrayAnimalList = [ { '名字' = 狗, 'animal_id' = 001 }, { '名字' = 老鼠, 'animal_id' = 002 }, { '名字' = 猫, 'animal_id' = 003 } ];

        这是一个帮助你获得排序数组的代码

        //here you have to pass key for which you want to sort data
        
         NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        
           NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
        
          // here you will get sorted array in 'sortedArray'
          NSMutableArray * sortedArray = [[arrayAnimalList sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-03
          • 1970-01-01
          • 2012-06-07
          • 2016-03-01
          • 1970-01-01
          相关资源
          最近更新 更多