Какова наилучшая практика для реализации NSCopying в иерархии наследования двух классов? Я хотел бы иметь глубокую копию свойств Square и Shape на копии.Правильный способ реализации NSCopying для класса hiearchy
В 3 вопросов, которые я:
- ли оба родителя и ребенок класса нужно объявить, что они реализации
NSCopying
или достаточно, чтобы только объявить его в базовом классе? - Я видел, как некоторые люди используют
[instance copy]
вместо[instance copyWithZone:]
Это просто предпочтение или правильнее использовать:copyWithZone
? - При копировании массивов, это правильно сделать:
newObj.list = [[NSArray alloc] initWithArray:self.list copyItems:YES];
Вот что у меня есть:
@interface Shape : NSObject <NSCopying>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *sides;
@property (nonatomic, strong) NSArray *list;
@end
@implementation Shape
- (id)copyWithZone:(NSZone *)zone {
Shape *shape = [[[self class] allocWithZone:zone] init];
// Is it correct to use copyWithZone: instead of copy? eg: [self.name copy]
shape->_name = [self.name copyWithZone:zone];
shape->_sides = [self.sides copyWithZone:zone];
shape->_list = [[NSArray alloc] initWithArray:self.list copyItems:YES];
return shape;
}
@end
// Does this class also need to declare <NSCopying>?
@interface Square : Shape
@property (nonatomic, strong) NSString *color;
@property (nonatomic, strong) NSArray *corners;
@end
@implementation Square
- (id)copyWithZone:(NSZone *)zone {
// Will this ensure a deep copy of the inherited properties?
Square *square = [[[self class] allocWithZone:zone] init];
square->_color = [self.color copyWithZone:zone];
square->_corners = [[NSArray alloc] initWithArray:self.corners copyItems:YES];
return square;
}
@end
возможный дубликат [Исполнительное NSCopying в Подкласс Подкласс] (HTTP: // StackOverflow. com/questions/4472904/implementation-nscopying-in-subclass-of-subclass) –
Сортировка. Я видел этот вопрос, но он не ответил на все мои вопросы. –
Пожалуйста, будьте более конкретными о своих вопросах. Что именно вы не понимаете? Что именно там не ответили? –