Quick Cocoa Tip
It took me a good 20 minutes to run down and find this bug in my code and I honestly can’t believe that it hasn’t come up before now. I thought that I would share in case anyone out there is banging their head against the table like I was.
I have a class called MBHand that contains a NSMutableArray as one of the key objects. So, on init, I need to set that array up to use. I thought I had that setup right. The error crept in with the following message:
-[NSCFArray addObject:]: mutating method sent to immutable object
Got to thinking and that leads back to my init method. I looked at my code and I had used the rather normal way of
1 2 3 4 5 6 | - (void)setArray:(NSMutableArray *)newArray { if ( array != newArray ) { [array release]; array = [newArray copy]; } } |
This method looked good, but I used array = [[NSMubableArray array] retain]; and it works fine. Therefore, it was in the setter method above. Yep, after looking at that, it hit me. I wasn’t making a mutable copy of the array passed it. Needs to have “array = [newArray mutableCopy]; ” and it works like a charm!
1 2 3 4 5 6 | - (void)setArray:(NSMutableArray *)newArray { if ( array != newArray ) { [array release]; array = [newArray mutableCopy]; } } |
Just a tip for all those newbies out there like me!














Submitting Your Comment, give me a second...
Hey M
thanks for that, I think it spent a lot more than 20 minutes on a similar bug. Tried to archive and then unarchive a NSMutableArray. Whatever way I tried, it came back immutable – but [theArray mutableCopy] worked!
Thanks again!