跨两个类继承层次结构实现NSCopying的最佳实践是什么?我想把正方形和形状的属性都印在一份副本上。
我有三个问题:
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发布于 2014-01-12 03:49:32
父类和子类都需要声明它们正在实现NSCopying,还是只在基类上声明它足够了?
这是风格的问题。我通常不会再次声明NSCopying,但如果不明显的话,它可能会提供一些清晰性。
我见过一些人使用实例复制而不是实例copyWithZone:这只是一种偏好还是使用: copyWithZone更正确?
打电话给copy是可以的。区域已经很长时间没有使用了(我不相信OS曾经使用过它们)。但是,您应该重写copyWithZone:。
在复制数组时,正确的做法是: newObj.list = [NSArray alloc initWithArray:self.list copyItems:YES];
是的,这是必要的,但如果数组中的对象没有在其copyWithZone:中实现深度副本,则这是不够的。注意,这调用的是copy,而不是mutableCopy。因此,如果您有一个可变数组,那么您将得到一个数组。如果您需要保持可更改性,则必须自己调用mutableCopy。
然而,你犯了一个错误:
// Will this ensure a deep copy of the inherited properties?
Square *square = [[[self class] allocWithZone:zone] init];不,你需要打电话:
Square *square = [super copy];https://stackoverflow.com/questions/21070863
复制相似问题