How do I add multiple objects to same key in an NSMutableDictionary
?
I cannot find the right method. The setObject
method only updates a single object in the key array. The method addObject: forkey:
in the NSMutableDictionary
isn't available and is causing a crash when it is used.
The dictionary is read from a plist
file.
The Dictionary:
temp = {
nickname : score
item 0 = level1;
item 1 = level2;
item 3 = level3;
score
item 0 = 400;
item 1 = 400;
item 3 = 400;
}
Here is the code:
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
str_nickname = [temp objectForKey:@"nickname"];
for (NSString *key in str_nickname){
if ([key isEqualToString:@"level2"]) { //replace object with new name
[newDict setObject:@"new level" forKey:@"nickname"];
} else {
[newDict addObject:key forKey:@"nickname"]; //wont work!!!
}
}
Also I want to update the new score in the new dictionary and have to update this at the corresponding level-object, maybe by the index?
if you want to have multiple objects stored under the same key in a dictionary, your only chance is putting them into an
and storing that in your dictionary. Reason is, dictionaries are key-value-PAIRINGS. The entire architecture isnt made to support a key that corresponds to more than one object. The objects would be indistuguishable for the system, hence, no dice.
EDIT: If you want to access the object by using an index, i guess your best bet is the Array-Version. Store a Mutable Array in your dictionary for the key "nickname", then add Objects to that array. To Store:
[myDictionary setObject:[NSMutableArray array] ForKey:@"nickname"];
[[myDictionary objectForKey:@"nickname"] addObject:yourObject];
To retrieve:
[[myDictionary objectForKey:@"nickname"] objectAtIndex:index];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With