我正在尝试清除有关实现的一些想法copyWithZone:
,任何人都可以对以下内容发表评论...
// 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中:
最好直接写类名
[[Crime allocWithZone:zone] init]
还是应该使用[[[self Class] allocWithZone:zone] init]
?可以
[self month]
用来复制iVar,还是应该直接访问iVar_month
?
NSCopying
。例如,NSObject
不这样做,因此调用[super copyWithZone: zone]
将引发异常。