我想允许我的类对象的深层副本,并尝试实现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
Run Code Online (Sandbox Code Playgroud)
我该如何创建这个类的深层副本?
你应该添加 NSCopying协议到类的接口.
@interface MyCustomClass : NSObject <NSCopying>
Run Code Online (Sandbox Code Playgroud)
那么方法应该是:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
NSObject不符合NSCopying协议.这就是你无法打电话的原因super copyWithZone:.
编辑:根据Roger的评论,我更新了copyWithZone:方法中的第一行代码.但根据其他评论,可以安全地忽略该区域.
| 归档时间: |
|
| 查看次数: |
3549 次 |
| 最近记录: |