首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现类NSCopying的正确方法

实现类NSCopying的正确方法
EN

Stack Overflow用户
提问于 2014-01-12 03:11:36
回答 1查看 778关注 0票数 2

跨两个类继承层次结构实现NSCopying的最佳实践是什么?我想把正方形和形状的属性都印在一份副本上。

我有三个问题:

  1. 父类和子类都需要声明它们正在实现NSCopying,还是只在基类上声明它足够了?
  2. 我见过一些人使用[instance copy]而不是[instance copyWithZone:],这只是一种首选,还是使用:copyWithZone更正确?
  3. 当复制数组时,这样做正确吗:newObj.list = [[NSArray alloc] initWithArray:self.list copyItems:YES];

我现在拥有的是:

代码语言:javascript
复制
@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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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

然而,你犯了一个错误:

代码语言:javascript
复制
// Will this ensure a deep copy of the inherited properties?
Square *square = [[[self class] allocWithZone:zone] init];

不,你需要打电话:

代码语言:javascript
复制
Square *square = [super copy];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21070863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档