How to set object and keys to NSMutabledictionary in correct order [duplicate]

℡╲_俬逩灬. 提交于 2020-01-17 16:34:09

问题


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

The code:

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

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

For example, currentArry is:

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

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

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

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?


回答1:


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

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

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.




回答2:


You can try my code:

NSArray *currentArry = @[@1,@3,@5,@10,@100,@500,@1000];
NSMutableDictionary *dict = [NSMutableDictionary new];
[currentArry enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [dict setObject:@0 forKey:obj];
}];

NSArray * sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];

[sortedKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"%@:%@",obj,dict[obj]);
}];

You didn't need to sorted dictionary - all you need it sorted keys, for getting data by this key.



来源:https://stackoverflow.com/questions/24142583/how-to-set-object-and-keys-to-nsmutabledictionary-in-correct-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!