如何以正确的顺序将对象和键设置为 NSMutabledictionary [英] How to set object and keys to NSMutabledictionary in correct order

查看:53
本文介绍了如何以正确的顺序将对象和键设置为 NSMutabledictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将特定键的对象设置为 for 循环中的 NSMutableDictionary

I am trying set objects for particular keys to an NSMutableDictionary in a for loop

代码:

for(int k =0;k<currenyArry.count;k++)
{
    [_currenies setObject:@"0" forKey:currenyArry[k]];
}

这里,_currenies 是一个 NSMutableDictionarycurrenyArry 是一个 NSMutableArray.

Here, _currenies is an NSMutableDictionary and currenyArry is an NSMutableArray.

例如,currentArry 是:

[1,3,5,10,100,500,1000];

_currenies字典中设置对象后,看起来像:

After setting the objects in _currenies dictionary, it looks like:

{1:"0",10:"0",100:"0",1000:"0",3:"0",5:"0",500:"0"}

但我需要基于我的 currenyArry 的订单,比如

But I need the order based on my currenyArry like

{1:"0",3:"0",5:"0",10:"0",100:"0",500:"0",1000:"0"}

如何修改我的代码来实现这一点?

How can I modify my code to achieve this?

推荐答案

这是正确答案 - NSDictionaryNSMutableDictionary 是基于哈希的容器,因此 无序.

This is the correct answer - NSDictionary and NSMutableDictionary are hash-based containers, which are therefore unordered.

要以特定顺序从 NSDictionary 获取数据,您可以对键进行排序,然后按照所需顺序从容器中提取数据:

To get your data from NSDictionary in a specific order, you can order the keys, and then pull the data from the container in the order that you want:

for (NSNumber *key in currenyArry) {
    NSLog(@"Key: %@ Value: %@", key, _currenies[key]);
}

这将按照 currenyArray 定义的顺序生成键值对.当然,您的代码可以根据需要进行任何其他处理,而不仅仅是打印键值对.

This will produce the key-value pairs in the order defined by teh currenyArray. Of course your code can do any other processing as needed, rather than simply printing key-value pairs.

这篇关于如何以正确的顺序将对象和键设置为 NSMutabledictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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