Error: no visible @interface for "NSObject" declares selector "copyWithZone":

I want to allow a deep copy of my class object and try to implement copyWithZone, but calling [super copyWithZone:zone] gives an 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 to create a deep copy of this class?

+4
source share
1 answer

You must add the NSCopying protocol to your class 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 does not comply with the NSCopying protocol. That is why you cannot call super copyWithZone:

Edit: based on Roger's comment, I updated the first line of code in the copyWithZone: method. But, based on other comments, the zone can be safely ignored.

+9
source

All Articles