问题
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