Dec 25

Recently I was working on some code that kept throwing

‘NSInternalInconsistencyException’, reason: ‘*** -[NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object’

and it made no sense to me because I was trying to modify an NSMutableArray. After some investigation I found that somewhere in the code, the NSMutableArray instance was being assigned an NSArray i.e. it was doing something similar to the simplified version below:

NSArray *array = [NSArray arrayWithObjects:@“one”, @“two”, @“three”, nil];
NSDictionary *dict = [NSDictionary dictionaryWithObject:array forKey:@“array”];
NSMutableArray *mutableArray;
mutableArray = [dict objectForKey:@“array”];
[mutableArray removeObjectAtIndex:0];

here, objectForKey method actually returns an NSArray which is being assigned to an NSMutableArray, thereby making it an NSArray itself. The issue here is that we are downcasting the pointer i.e. we are assigning a parent class pointer to a child class pointer, may be Apple should implement explicity casting like C++. To fix it, use:

[[dict objectForKey:@“array”] mutableCopy];

Hitting this error is fairly easy e.g. one may be loading user preferences fromĀ  NSUserDefaults or application data/settings from a plist.

written by ishaq \\ tags: ,