JAY RAPARKA
JAY RAPARKA

Reputation: 1326

Mutating method sent to immutable object with NSMutableArray

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.

Upvotes: 1

Views: 2284

Answers (1)

JAY RAPARKA
JAY RAPARKA

Reputation: 1326

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.

Upvotes: 8

Related Questions