排序NSMutableDictionary [英] Sort an NSMutableDictionary

查看:161
本文介绍了排序NSMutableDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSMutableDictionary NSString 映射到 NSString (虽然值为 NSStrings ,但它们只是整数)。



例如考虑以下映射,

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

我想最终得到字典中排名前10位的词条,价值的顺序。有人可以向我显示代码吗?也许有一个数组的键和另一个值的数组。但是,我不介意我只是想要有效率。



谢谢!

解决方案>

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



您可以使用以下值获取值:

  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
返回NSOrderedSame;
}


I have an NSMutableDictionary that maps NSString to NSString (although the values are NSStrings, they are really just integers).

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.

Thank you!

解决方案

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:.

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

[values sortedArrayUsingFunction:comparatorFunction context:nil]

Being comparatorFunction (from 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;
}

这篇关于排序NSMutableDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆