0
votes

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

1
Note that you can set a breakpoint on exceptions (in the Breakpoint navigator on the left pane, click on the + icon at the bottom). This will let you see where the exception is thrown and get a backtrace. You will see that addObject: actually calls insertObject:atIndex: which in turn throws the exception :) - Taum

1 Answers

4
votes

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.