使用-mutableCopyWithZone:在自定义类上使它不可变 [英] Using -mutableCopyWithZone: on custom class makes it immutable

查看:598
本文介绍了使用-mutableCopyWithZone:在自定义类上使它不可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个符合 NSCopying NSMutableCopying 的自定义类。

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

我为 -copyWithZone: -mutableCopyWithZone:添加了一个实现,但是每当我在我的对象上调用 -mutableCopy 并尝试调用另一个方法时,它崩溃,因为一些ivars变得不可变,即使我调用

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];

+ flip: ,因为它试图在上使用 removeObjectAtIndex: addObject: NSMutableArray ivar)

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

任何帮助赞赏。

推荐答案

我最后的想法:如果 setArray: / code>和 setObjects:方法实际上是声明为 @property(copy)的属性的setter它们将复制传递的数组 - 并且 copy 总是返回一个不可变的对象。在这种情况下,解决这个问题的简单方法是将它们声明为(retain)而不是(copy)

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

这篇关于使用-mutableCopyWithZone:在自定义类上使它不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆