NSDictionary 按浮点数形式对键进行排序
基本上我有一个带有键和值的 NSDictionary。
键都是数字,但目前它们是字符串。
我希望能够将它们作为数字进行比较以便对它们进行排序。
例如:如果我有一个这样的字典:
{
"100" => (id)object,
"20" => (id)object,
"10" => (id)object,
"1000" => (id)object,
}
我希望能够像这样排序:
{
"10" => (id)object,
"20" => (id)object,
"100" => (id)object,
"1000" => (id)object,
}
有什么想法吗?
谢谢
汤姆
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,
}
Any ideas?
Thanks
Tom
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定你在做什么——字典本质上是未排序的,默认实现中没有稳定的键排序。如果你想通过排序键遍历值,你可以这样做:
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:
您无法对字典进行排序,但可以将键作为数组获取,对其进行排序,然后按该顺序输出。 sortedArrayUsingComparator 会执行此操作,您可以将字符串与 NSNumericSearch 选项进行比较。
You can't sort a dictionary, but you can get the keys as an array, sort that, then output in that order. sortedArrayUsingComparator will do that, and you can compare the strings with the NSNumericSearch option.
将
compare:options:
与NSNumericSearch
结合使用。Use
compare:options:
withNSNumericSearch
.