错误:'NSObject'没有可见的@interface声明选择器'copyWithZone:'。

4

我希望允许对我的类对象进行深拷贝,并尝试实现copyWithZone方法,但调用[super copyWithZone:zone]时出现错误:

error: no visible @interface for 'NSObject' declares the selector 'copyWithZone:'

@interface MyCustomClass : NSObject

@end

@implementation MyCustomClass

- (id)copyWithZone:(NSZone *)zone
{
    // The following produces an error
    MyCustomClass *result = [super copyWithZone:zone];

    // copying data
    return result;
}
@end

我该如何创建这个类的深度拷贝?

1个回答

9
你应该在你的类接口中添加 NSCopying 协议。
@interface MyCustomClass : NSObject <NSCopying>

那么这个方法应该是:

首先:

- (id)copyWithZone:(NSZone *)zone {
    MyCustomClass *result = [[[self class] allocWithZone:zone] init];

    // If your class has any properties then do
    result.someProperty = self.someProperty;

    return result;
}

NSObject不符合NSCopying协议。这就是为什么你不能调用super copyWithZone:的原因。

编辑:根据Roger的评论,我已经更新了copyWithZone:方法中的第一行代码。但是基于其他评论,可以安全地忽略区域。


这是正确的。我写了一个类似的答案,但他比我先回答了 :) - Kibitz503
你的回答完全忽略了时区。请参考https://dev59.com/p2kw5IYBdhLWcg3waZ74。 - Roger Binns
@RogerBinns 请参考https://dev59.com/NW445IYBdhLWcg3w7uc0?rq=1的被接受答案。 - rmaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接