Ошибка: нет видимого @interface для 'NSObject' объявляет селектор 'copyWithZone:'
Я хочу разрешить глубокое копирование моего объекта класса и пытаюсь реализовать 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
Как мне создать глубокую копию этого класса?
1 ответ
Решение
Вы должны добавить 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:
метод. Но, основываясь на других комментариях, зону можно смело игнорировать.