I want to allow deep copy of my class object and am trying to implement copyWithZone but the call to [super copyWithZone:zone]
yields the error:
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
How should I create a deep copy of this class?
You should add the NSCopying
protocol to your class's interface.
@interface MyCustomClass : NSObject <NSCopying>
Then the method should be:
- (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
doesn't conform to the NSCopying
protocol. This is why you can't call super copyWithZone:
.
Edit: Based on Roger's comment, I have updated the first line of code in the copyWithZone:
method. But based on other comments, the zone can safely be ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With