Reputation: 49
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?
Upvotes: 5
Views: 8815
Reputation: 1742
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];
Upvotes: 2
Reputation: 3580
if your plist file is like this "test.plist"
The Dictionary temp={
nickname : Junaid Sidhu
levels
item 0 = level1;
item 1 = level2;
item 3 = level3;
score
item 0 = 400;
item 1 = 400;
item 3 = 400;
}
Here is the code
NSDictionary *temp = [[NSDictionary alloc]initWithContentsOfFile:[NSBundle mainBundle] pathForResource:@"test" ofType:@"plist"]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSString *str_nickname = [temp objectForKey:@"nickname"];
NSMutableArray *levels = [NSMutableArray new];
NSMutableArray *score = [NSMutableArray new];
for (NSString *key in [temp allKeys]){
if ( [key isEqualToString:@"levels"]) { //replace object with new name
levels = [NSMutableArray arrayWithArray:(NSArray *)[temp objectForKey:key]];
}
else if ( [key isEqualToString:@"score"]){
score = [NSMutableArray arrayWithArray:(NSArray *)[temp objectForKey:key]];
}
}
NSLog(@"Nick : %@ \n levels : %@ \n score : %@ \n",str_nickname,levels,score)
Upvotes: 1