Using -mutableCopyWithZone: on custom class makes it immutable

£可爱£侵袭症+ 提交于 2020-01-05 06:54:27

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/14841130/using-mutablecopywithzone-on-custom-class-makes-it-immutable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!