2012-11-29 41 views
4

我希望让我的类对象的深拷贝和想实现copyWithZone但调用[super copyWithZone:zone]产生了错误:错误:“NSObject的”不可见@interface声明选择“copyWithZone:”

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 

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

回答

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:

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

+0

这是正确的。我写了一个类似的答案,但他打我:) – Kibitz503

+0

你的答案完全忽略了区域。请参阅http://stackoverflow.com/questions/9907154/ –

+0

@RogerBinns请参阅接受的答案http://stackoverflow.com/questions/4631526/iphone-idcopywithzonenszone-zone-what-is-zone-for?rq=1 – rmaddy

相关问题