NSArray can be mutable!


I’ve been fooling around with stuff, trying to fully understand the contents of the book, and have revisited this chapter because I found that in some cases NSArray is (or appears to be) mutable. I’m sure it isn’t, so what’s going on here? First, I started with this:

NSArray *theArray = [[NSArray alloc] initWithObjects: @"three", @"four", @"five", nil]; NSLog(@" Does addObject work on theArray? %d", [theArray respondsToSelector: @selector (addObject)]);
which returns as false, and sure enough:

was sick all over the carpet.

But then I set up theArray differently:

NSString *arrayData = @"three, four, five"; NSArray *theArray = [arrayData componentsSeparatedByString: @","]; NSLog(@" Does addObject work on theArray? %d", [theArray respondsToSelector: @selector (addObject)]);
and again the return was false, but then:

[theArray addObject: @"six"]; for (NSString *theString in theArray) { NSLog(@"%@", theString); }
returned all four values, with no errors and only the expected compiler warning. Is theArray simehow mutable because of the way it was initialised?


I think you meant @selector (addObject:), note the colon after the name, because addObject: takes a single argument, the object to be added.


OK, well spotted. So I made the change to the code, and now the respondsToSelector method retuns true both times, seemingly indicating that NSArray is indeed mutable. But nothing changes regarding the operation of the code - in the first case, vomit, in the second, rapture. So I’m left believing that NSArray is mutable in some cases, which is not what the docs lead me to expect.