Why would an instance of NSMutableArray be immutable?


 



On May 28, 2019, at 9:38 AM, James Walker <list2@...> wrote:

 po [formatsOfSize isKindOfClass: [NSMutableArray class]]

and the reply was '\x01'.  So it should be mutable, no?

Nope. This is due to the way CF bridging works — the magic class __NSCFArray (?) is bridged to CFArray and CFMutableArray. To support mutable arrays, that means __NSCFArray has to subclass NSMutableArray. So all bridged NSArrays subclass NSMutableArray, whether or not the instance is mutable.

 Is there a better run-time test for mutability?

There is no good test other than seeing if it throws an exception when you try to mutate it. :-p

At some point in your code you improperly cast something to NSMutableArray when you didn’t actually have a guarantee it was mutable; you may need to do a code review to figure out where. 

(It can be hard to tell, since Obj-C lets you implicitly cast from ‘id’ to an explicit class. I sometimes grouse about C++ making me write these explicitly, but it does make it clearer where I’m doing the type-casts.)

—Jens


James Walker
 

I was trying to add an object to an array and got an exception saying that I was trying to modify an immutable object. I set a breakpoint just before the addObject: line, and said to lldb

po [formatsOfSize isKindOfClass: [NSMutableArray class]]

and the reply was '\x01'. So it should be mutable, no? Is there a better run-time test for mutability?

If it's a clue,

po [formatsOfSize class]

produced

__NSCFArray
.