NSDictionary按键排序为浮点数 [英] NSDictionary sort by keys as floats
本文介绍了NSDictionary按键排序为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我有一个带有键和值的NSDictionary。
basically I have an NSDictionary with keys and values.
键都是数字,但目前它们是字符串。
The keys are all numbers, but at the moment they are strings.
我希望能够将它们作为数字进行比较以便对它们进行排序。
I want to be able to compare them as numbers in order to sort them.
例如:如果我有这样的字典:
eg: If I have a Dictionary like this:
{
"100" => (id)object,
"20" => (id)object,
"10" => (id)object,
"1000" => (id)object,
}
我希望能够像这样排序:
I want to be able to sort it like this:
{
"10" => (id)object,
"20" => (id)object,
"100" => (id)object,
"1000" => (id)object,
}
任何想法?
谢谢
Tom
推荐答案
不确定你要做什么 - 词典本质上是未排序的,默认实现中没有稳定的键排序。如果你想按排序键遍历值,你可以这样做:
Not sure what you are up to – dictionaries are inherently unsorted, there is no stable key ordering in the default implementation. If you want to walk the values by sorted keys, you can do something like this:
NSInteger floatSort(id num1, id num2, void *context)
{
float v1 = [num1 floatValue];
float v2 = [num2 floatValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
NSArray *allKeys = [aDictionary allKeys];
NSArray *sortedKeys = [allKeys sortedArrayUsingFunction:floatSort context:NULL];
for (id key in sortedKeys)
id val = [aDictionary objectForKey:key];
…
这篇关于NSDictionary按键排序为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文