views:

43

answers:

3

Hi friends,

I have used NSMutable Dictionary and NSMutable Array. The datas are to be stored and retrieved from plist(Documents Directory) using NSArray of NSMutable Dictionary.

     Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object' 

Please Guide me why its happened?.

Thanks!

A: 

you said you are retrieving the array as a NSArray and not casting it to a NSMutableArray before you attempt to remove an object for it. This causes an error since you can't remove an object from an NSArray

Jesse Naugher
A: 

Suppose [something dictionaryValue] returns an immutable dictionary, and you want a mutable version of that dictionary. It is not enough to say:

NSMutableDictionary *d = [something dictionaryValue];

This merely tells the compiler that d is an NSMutableDictionary, but really it's the same immutable dictionary you got from [something dictionaryValue]. Instead, you need to create a new, mutable copy of the dictionary:

NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:
                                              [something dictionaryValue]];

Similarly, use [NSMutableArray arrayWithArray:...] for arrays.

David M.
+2  A: 

It might help if you post the exact code that causes. My guess would be that while you are using NSMutableDictionary, the call to valueForKey: returns to you a non-mutable NSArray, and you think it is returning you an NSMutableArray instance. Note that mutable arrays and dictionaries allow you to manipulate the collection of items inside them, but do not guarantee you that those items themselves are mutable. For example, if you check the Property List Programming Guide: Reading and Writing Property-List Data, you will notice the following example:

If you load the property list with this call:

NSMutableArray * ma = [NSMutableArray arrayWithContentsOfFile:xmlFile];

ma is a mutable array with immutable dictionaries in each element. Each key and each value in each dictionary are immutable.

If you need explicit control over the mutability of the objects at each level, use propertyListFromData:mutabilityOption:format:errorDescription:

You can also create an explicit NSMutableArray copy from the NSArray you got from the NSMutableDictionary.

Franci Penov
+1, Thanks for your Answer.
Pugal Devan
Btw, your accept rate is a bit low. :-P
Franci Penov
Thanks for your feedback...
Pugal Devan