user1504605
user1504605

Reputation: 589

exception: "mutating method sent to immutable object" which is actually a mutable array

I am trying to change the value to a specific key for a mutable array:

NSMutableArray* reversed = [NSMutableArray arrayWithArray:regions];

[reversed setValue:@"current" forKey:@"region"];

But this leads to an uncaught exception:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' * First throw call stack:

Why is it telling me that my NSMutableArray is an immutable object?

Upvotes: 0

Views: 136

Answers (2)

Tricertops
Tricertops

Reputation: 8512

Do you see any mention of NSMutableArray in that error message? No. It mentions __NSCFDictionary, which is an NSDictionary runtime class.

Your call to setValue:forKey: is being forwarded to all objects in this array. At least one of those objects is an immutable NSDictionary, which throws this exception.

Upvotes: 1

nneonneo
nneonneo

Reputation: 179422

setValue:forKey: is documented to do the following:

setValue:forKey:

Invokes setValue:forKey: on each of the array's items using the specified value and key.

Emphasis mine. Your NSMutableArray is mutable, but one of the items contained within is not mutable.

Upvotes: 2

Related Questions