【问题标题】:error: no visible @interface for 'NSObject' declares the selector 'copyWithZone:'错误:“NSObject”没有可见的@interface 声明选择器“copyWithZone:”
【发布时间】:2015-08-10 07:58:20
【问题描述】:

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

我应该如何创建这个类的深层副本?

【问题讨论】:

    标签: ios copywithzone


    【解决方案1】:

    您应该将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: 方法中的第一行代码。但基于其他 cmets,可以放心地忽略该区域。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多