实现copyWithZone时的最佳做法: [英] Best practice when implementing copyWithZone:

查看:332
本文介绍了实现copyWithZone时的最佳做法:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想清除一些关于实现 copyWithZone:的问题,任何人都可以评论以下内容...

I am trying to clear up a few things in my head about implementing copyWithZone:, can anyone comment on the following ...

// 001: Crime is a subclass of NSObject.
- (id)copyWithZone:(NSZone *)zone {
    Crime *newCrime = [[[self class] allocWithZone:zone] init];
    if(newCrime) {
        [newCrime setMonth:[self month]];
        [newCrime setCategory:[self category]];
        [newCrime setCoordinate:[self coordinate]];
        [newCrime setLocationName:[self locationName]];
        [newCrime setTitle:[self title]];
        [newCrime setSubtitle:[self subtitle]];
    }
    return newCrime;
}

// 002: Crime is not a subclass of NSObject.
- (id)copyWithZone:(NSZone *)zone {
    Crime *newCrime = [super copyWithZone:zone];
    [newCrime setMonth:[self month]];
    [newCrime setCategory:[self category]];
    [newCrime setCoordinate:[self coordinate]];
    [newCrime setLocationName:[self locationName]];
    [newCrime setTitle:[self title]];
    [newCrime setSubtitle:[self subtitle]];
    return newCrime;
}



在001:



In 001:


  1. 最好直接编写类名 [[Crime allocWithZone:zone] init] 或者应该使用 [[[Class] allocWithZone:zone] init]

c> [self month] 复制iVars或者直接访问iVars,即 _month

Is it ok to use [self month] for copying the iVars or should I be accessing the iVars directly i.e. _month?


推荐答案


  1. 您应该始终使用 [[ self class] allocWithZone:zone] ,以确保您正在使用适当的类创建副本。你给002的例子显示了为什么:子类将调用 [super copyWithZone:zone] ,并期望获得适当类的实例,而不是超级实例类。

  1. You should always use [[self class] allocWithZone:zone] to make sure you are creating a copy using the appropriate class. The example you give for 002 shows exactly why: Subclasses will call [super copyWithZone:zone] and expect to get back an instance of the appropriate class, not an instance of the super class.

我直接访问ivars,所以我不需要担心任何可能添加到属性设置器的副作用) 稍后的。请记住,子类可以自由覆盖任何方法。在您的示例中,您每个ivar发送两个额外的消息。我将执行如下:

I access the ivars directly, so I don't need to worry about any side effects I might add to the property setter (e.g., generating notifications) later on. Keep in mind, subclasses are free to override any method. In your example, you are sending two extra messages per ivar. I would implement it as follows:

代码:

- (id)copyWithZone:(NSZone *)zone {
    Crime *newCrime = [super copyWithZone:zone];
    newCrime->_month = [_month copyWithZone:zone];
    newCrime->_category = [_category copyWithZone:zone];
    // etc...
    return newCrime;
}

当然,无论您复制ivars,保留它们,应该镜像设置器做什么。

Of course, whether you copy the ivars, retain them, or just assign them should mirror what the setters do.

这篇关于实现copyWithZone时的最佳做法:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆