Ios 错误:';没有可见的@接口;NSObject';声明选择器';copyWithZone:&x27;

Ios 错误:';没有可见的@接口;NSObject';声明选择器';copyWithZone:&x27;,ios,copywithzone,Ios,Copywithzone,我希望允许类对象的深度复制,并尝试实现copyWithZone,但调用[super copyWithZone:zone]会产生错误: error: no visible @interface for 'NSObject' declares the selector 'copyWithZone:' @interface MyCustomClass : NSObject @end @implementation MyCustomClass - (id)copyWithZone:(NSZone

我希望允许类对象的深度复制,并尝试实现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

如何创建此类的深度副本?

您应该将
NSCopying
协议添加到类的接口中

@interface MyCustomClass : NSObject <NSCopying>
NSObject
不符合
NSCopying
协议。这就是为什么您不能调用
超级copyWithZone:


编辑:根据罗杰的评论,我更新了
copyWithZone:
方法中的第一行代码。但根据其他评论,可以安全地忽略该区域。

这是正确的。我写了一个类似的答案,但他打败了我:)你的答案完全忽略了区域。请参阅@RogerBinns查看已接受的答案
- (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;
}