我想澄清有關實現copyWithZone:
在我的頭上的幾件事情,在下面的任何人都可以評論...最佳實踐實施時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]
來複制iVars,還是應該直接訪問iVars,即_month
?
選擇哪兩種方法取決於超是否實現'NSCopying'。例如,'NSObject'不會,所以調用'[super copyWithZone:zone]'會拋出異常。 – Costique 2012-03-29 05:29:32
它說/用戶/ ws403216 /桌面/演示/演示/犯罪。m:21:28:'NSObject'沒有可見的@interface聲明選擇器'copyWithZone:'在我的情況下,超類的Crime.m是NSObject。 – 2014-04-30 07:05:30
@NitinMalguri正如前面的評論指出的,如果父類支持NSCopying,你應該只調用'[super copyWithZone:zone]',否則你應該調用'[[[self class] allocWithZone:zone] init]'並複製字段按要求。 – Tony 2014-05-08 17:35:41