ios 对 NSMutableDictionary 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4558639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:24:06  来源:igfitidea点击:

Sort an NSMutableDictionary

iosdictionarynsmutabledictionary

提问by CodeGuy

I have an NSMutableDictionarythat maps NSStringto NSString(although the values are NSStrings, they are really just integers).

我有一个NSMutableDictionary映射NSStringNSString(尽管值是NSStrings,但它们实际上只是整数)。

For example consider the following mappings,

例如考虑以下映射,

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

I'd like to end up with the top 10 entries in the dictionary sorted by decreasing order of the value. Can someone show me code for this? Perhaps there is an array of keys and another array of values. However it is, I don't mind. I'm just trying to have it be efficient.

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

Thank you!

谢谢!

回答by HyLian

Get the Array of the Values, sort that array and then get the key corresponding to the value.

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

You can get the values with:

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

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

But, if the collection is as you show in your example, (I mean, you can infer the value from the key), you can always sort the keys instead messing with the values.

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

Using:

使用:

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

The comparator is a message selector which is sent to the object you want to order.

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

If you want to order strings, then you should use a NSString comparator. The NSString comparators are i.e.: caseInsensitiveCompare or localizedCaseInsensitiveCompare:.

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

If none of these are valid for you, you can call your own comparator function

如果这些都对您无效,您可以调用自己的比较器函数

[values sortedArrayUsingFunction:comparatorFunction context:nil]

Being comparatorFunction (from AppleDocumentation)

作为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;
}

回答by kraftydevil

Use this method:

使用这个方法:

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

Call it and then create a new dictionary with keys sorted by value:

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

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

回答by Luis Andrés García

The simplest way is:

最简单的方法是:

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

回答by hburde

Sorting the keys and using that to populate an array with the values:

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

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

回答by iDilip

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
[unsortedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
recentSortedArray = [stories copy];

回答by Bhupendrasingh Lohar

if you want to sort data in ascending order for key 'name' for such kind of Example then this may help you.

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

arrayAnimalList = [ { 'name' = Dog, 'animal_id' = 001 }, { 'name' = Rat, 'animal_id' = 002 }, { 'name' = Cat, 'animal_id' = 003 } ];

arrayAnimalList = [ { 'name' = Dog, 'animal_id' = 001 }, { 'name' = Rat, 'animal_id' = 002 }, { 'name' = Cat, 'animal_id' = 003 }];

This is a code which help you to get sorted array

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

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