Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: no visible @interface for 'NSObject' declares the selector 'copyWithZone:'

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?

like image 816
Howard Spear Avatar asked Jan 14 '23 21:01

Howard Spear


1 Answers

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.

like image 159
rmaddy Avatar answered Jan 26 '23 20:01

rmaddy