I’m have a little bit of trouble storing and accessing a multidimensional array from NSUserDefault. Any help would be appreciated. The error I get when I run this code is “* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'”
//To create, add values to and store arrays
multiArray = [[NSArray alloc] init];
multiArray = [NSArray arrayWithObjects:[NSMutableArray array], [NSMutableArray array], [NSMutableArray array], nil];
[[multiArray objectAtIndex:0] addObject:[NSNumber numberWithDouble:number1]];
[[multiArray objectAtIndex:1] addObject:[NSNumber numberWithDouble:number2]];
[[multiArray objectAtIndex:2] addObject:[NSNumber numberWithDouble:number3]];
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults]
[standardUserDefaults setObject:multiArray forKey:@"multiArray"];
[standardUserDefaults synchronize];
//To access the array
NSArray *multiArrayCopy = [[NSArray alloc] init];
multiArrayCopy = [[standardUserDefaults objectForKey:@"multiArray"] mutableCopy];
NSLog(@"array count is %i", [[multiArrayCopy objectAtIndex:2] count]);
Label1.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:0] objectAtIndex:0]];
Label2.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:1] objectAtIndex:0]];
Label3.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:2] objectAtIndex:0]];
You are getting the error because [NSMutableArray array] is a class method of NSArray that returns an empty (non-mutable) array. Remember that NSMutableArray is a sub-class of NSArray. Try creating NSMutableArray list, thusly:
Also, I think multiArray should be NSMutableArray as well. Try this to see if the error goes away.
If it does not work, try breaking apart the logic to the simplest elements. Can you save and get back single dimensional array with your objects? That is, what happens if you do the following?
When you get that working, then try nesting it into another mutable array, thusly:
This should work.