Doug
Doug

Reputation: 869

Mutating method sent to Immutable object - Where?

Kind of stuck on this error.

Pretty basic error

2012-07-20 12:44:07.462 Picsilk[4286:17903] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

I know this means somewhere in my code I am trying to insert an object into an NSArray rather than an NSMutableArray.

However, I don't use the method insertObject:atIndex: -anywhere- in my application.

Seriously, I did a search for "insert" across all of the files in my project and turned up nothing.

After doing some searching with breakpoints, I've found that the problem seems to arise when I use addObject to store an NSMutableDictionary object in an NSMutableArray object which is contained in the NSUserDefaults standardUserDefaults object

NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];

if(![userDef objectForKey:@"somekey"])
    [userDef setObject:[[NSMutableArray alloc] init] forKey:@"somekey"];

NSMutableDictionary *data = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"somehtmlstring", @"someid", nil] forKeys:[NSArray arrayWithObjects:@"data",@"id", nil ]];


    [[userDef objectForKey:@"somekey"] addObject:data  ];

The error happens right on that last line. Pretty sure everything is mutable, though. Should I not be using NSUserDefaults like this?

Also, this is obviously a watered-down version of my actual code. Pretty sure I've included everything relevant but I can post the actual code/purpose if needed.

Thanks

Upvotes: 0

Views: 459

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185681

NSUserDefaults is not a regular collection. It does not hold whatever you give it. -[NSUserDefaults objectForKey:] will always give you back an immutable object of the appropriate type.

Upvotes: 4

Related Questions