objective-ccocoaclassnscopyingnsmutablecopying

Using -mutableCopyWithZone: on custom class makes it immutable


I've created a custom class which conforms to NSCopying and NSMutableCopying.

I've added an implementation for -copyWithZone: and -mutableCopyWithZone:, but whenever I call -mutableCopy on my object and try to call another method, it crashes because some of the ivars have become immutable, even though I call -mutableCopyWithZone: on the ivars.

Here's how I'm copying my class:

MyObject *flipped = [list mutableCopy];
[MyObject flip:flipped];

(the code fails on +flip:, because it tries to use removeObjectAtIndex: and addObject: on a NSMutableArray ivar)

Here's how I'm copying the class:

- (id)mutableCopyWithZone:(NSZone *)zone {

    id instance = nil;

    if ((instance = [[[self class] alloc] init])) {

        [instance setArray:[self.array mutableCopyWithZone:zone]];
        [instance setObjects:[self.objects mutableCopyWithZone:zone]];

        [instance setItemCount:self.itemCount];

    }

    return instance;

}

I'm not sure why it's failing, but I really don't understand why it isn't making array and objects mutable.

Any help appreciated.


Solution

  • My last idea: if the setArray: and setObjects: methods are actually setters for properties declared as @property (copy), then they'll copy the arrays passed in - and copy always returns an immutable object. In this case, the easy way to fix this would be declaring them as (retain) instead of (copy).