Removing item from nested dictionary
I have this code and am trying to remove an item from a nested dictionary, then write the dictionary back out to NSUserdefaults. If I load a new driver then go back and try to remove it, the program crashes. Here is my code for removing.
-(void)Remove:(id)sender
{
subsDict = [[[[[NSUserDefaults standardUserDefaults] objectForKey:@"Subs"]retain] mutableCopy]autorelease];
NSLog(@"%@",modelDict);
NSLog(@"Removing Size %@",driverSize);
[[[subsDict objectForKey:driverBrand]objectForKey:driverModel]removeObjectForKey:driverSize]; //Crashes here
[self updateSizes];
NSLog(@"New sizearray:%i",[sizeArray count]);
if ([sizeArray count] == 0)
{
[brandDict removeObjectForKey: driverModel];
[self updateModels];
NSLog(@"New modelarray count:%i",[modelArray count]);
NSLog(@"driver model: %@ Modelarray %@",driverModel, modelArray);
if ([modelArray count] == 0) {
[subsDict removeObjectForKey:driverBrand];
}
}
NSLog(@"New subdict:%@",subsDict);
NSUserDefaults *userDefaults =开发者_StackOverflow中文版 [NSUserDefaults standardUserDefaults];
[userDefaults setObject:subsDict forKey:@"Subs"];
[userDefaults synchronize];
}
The error message you're getting indicates that the dictionary you're trying to modify is an NSDictionary, not an NSMutableDictionary.
You call mutableCopy
on the object returned from the NSUserSettings, which does make that a mutable dictionary. But it does not change any of the values. In particular, the dictionary that is the value for the key driverBrand
is still immutable, as it the dictionary inside it for the key driverModel
.
To do what you're wanting to do here, you'd have to make a mutable copy of each subdictionary along the way and assign it back into its parent.
Also, BTW, you have an extra retain that will be leaking memory in your first line. It should be [[[[NSUserDefaults standardUserDefaults] objectForKey:@"Subs"] mutableCopy] autorelease]
.
精彩评论