1
votes

I have found the Error Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' when i add object to mutable array at second time first time added successfully but second time it is crash the app i think there is problem with when i added object to array. Below code is crash.

- (void) viewWillAppear:(BOOL)animated
{

    if ([defaults objectForKey:@"Groups"] != nil)
    {
        NSLog(@"not nil defaults.");
        arrGroups = (NSMutableArray *)[defaults objectForKey:@"Groups"];
    }
    else
    {
        NSLog(@"nil defaults.");
        arrGroups = [[NSMutableArray alloc] init];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

NSLog(@"button index == %ld",(long)buttonIndex);
//txtCategory = [[alertView textFieldAtIndex:0] text];

if (buttonIndex == 1)
{
    //[self addingCategory:self];
    NSLog(@"Adding Group name = %@",[[alertView textFieldAtIndex:0]text]);
    [arrGroups addObject:[[alertView textFieldAtIndex:0]text]]; **//Crash here! at the time of add second object or also when i remove first object**
    NSLog(@"Added to array.");
    [defaults setObject:arrGroups forKey:@"Groups"];
    [defaults synchronize];
    //[defaults release];
    [tblGroups reloadData];
}

}

when i remove first object at that time i replace the userdefault with updated array so there is no problem i think. and i did not found proper reason for that crash.

so please support me either understood me the problem or solution but without understand the problem i can't understood solution so please any one tell that why this happen.

Thanks.

1
Is defaults has already some data? is it Dictionary? - Yohan
No its a NSUserDefaults and now i solve this prob but not finally understood why it is so if you found than just tell me the what i'm lake off. - JAY RAPARKA
How you copying data to arrGroups is it mutable or immutable array? - Yohan
May be you should use mutableCopy method. - Yohan
Thanks for the help. - JAY RAPARKA

1 Answers

7
votes

The problem with assigning to a NSMutableArray is, it will only work if defaultDefects was assigned an NSMutableArray for the given key.

Note: NSUserDefaults always returns an immutable object.

Do this instead

NSMutableArray *arrGroups = [[defaults objectForKey:@"Groups"]mutableCopy];

this guarantees a mutable copy.

Another way is.

arrGroups = [[NSMutableArray alloc]initWithArray:[defaults objectForKey:@"Groups"]]; //in your viewWillAppear where you assign array from defaults.