【发布时间】:2014-01-30 23:50:09
【问题描述】:
在两个类继承层次结构中实现 NSCopying 的最佳实践是什么?我想在副本上同时拥有 Square 和 Shape 属性的深层副本。
我有 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
【问题讨论】:
-
有点。我确实看到了这个问题,但它并没有回答我的所有问题。
-
那么,请对您的问题更具体一些。你到底有什么不明白的?究竟有什么没有回答?
标签: objective-c