Search code examples
iphonexcode4nsmutabledictionary

how to update NSMutableDictionary


I have

NSMutableDictionary *mutDic;

its loaded with some values from other NSMutableDictionary from an alert i am trying to update its value

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.mutDic setValue:[[alertView textFieldAtIndex:0] text] forKey:@"lname"];
}

but i am getting this exception

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

how we can update dictionary ?


Solution

  • I had the same exception before even though my dictionary was mutable.
    Let me explain my scenario to you, may be it will help :
    I had NSMutableArray of NSMutableDictionary,

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict = [array objectAtIndex:0];
    

    [dict setObject:@"" forKey:@""]; <-- it was crashing on this line...

    so I changed my code as below,

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[array objectAtIndex:0]];
    

    it worked fine :)