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!

Comments (1) Leave a Comment
  1. tom June 19th, 2007 at 18:21 | #1

    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!

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">
  1. No trackbacks yet.