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



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

那么方法应该是:

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

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

最新更新