Tôi cố gắng để làm sáng tỏ một vài điều trong đầu của tôi về việc thực hiện copyWithZone:
, bất cứ ai có thể nhận xét về sau ...Thực hành tốt nhất copyWithZone khi thực hiện:
// 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;
}
Trong 001:
Tốt nhất là viết tên lớp học trực tiếp
[[Crime allocWithZone:zone] init]
hoặc tôi nên sử dụng[[[self Class] allocWithZone:zone] init]
?Có thể sử dụng
[self month]
để sao chép iVars hoặc tôi có nên truy cập trực tiếp vào iVars tức là_month
không?
nào trong hai cách tiếp cận để lựa chọn phụ thuộc vào việc thực hiện lớp cha 'NSCopying'. Ví dụ, 'NSObject' không, do đó, gọi' [super copyWithZone: zone] 'sẽ ném một ngoại lệ. – Costique
Nó nói/Người dùng/ws403216/Máy tính để bàn/Demo/Demo/Tội phạm.m: 21: 28: Không hiển thị @interface cho 'NSObject' khai báo bộ chọn 'copyWithZone:' Siêu lớp Crime.m trong trường hợp của tôi là NSObject. –
@NitinMalguri Như chú thích trước đó chỉ ra, bạn chỉ nên gọi '[super copyWithZone: zone]' nếu lớp cha hỗ trợ NSCopying, nếu không bạn nên gọi '[[[class] allocWithZone: zone] init]' và copy fields theo yêu cầu. – Tony