【发布时间】:2013-11-21 06:06:15
【问题描述】:
我已经看到了两种不同的实现 copyWithZone 的方法。 它们有什么不同吗?
第一个代码:
@interface Person : NSObject <NSCopying>
@property (nonatomic,weak) NSString *name;
@property (nonatomic,weak) NSString *surname;
@property (nonatomic,weak) NSString *age;
-(id) copyWithZone:(NSZone *)zone;
@end
//and 1st implementation
@implementation Person
-(id) copyWithZone:(NSZone *)zone
{
Person *copy = [[self class] allocWithZone:zone];
copy.name = self.name; //should we use copy.name=[self.name copyWithZone: zone]; ?
copy.age = self.age;
copy.surname = self.surname; //here we make assignment or copying?
return copy;
}
@end
和第二个代码
@interface YourClass : NSObject <NSCopying>
{
SomeOtherObject *obj;
}
// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
// We'll ignore the zone for now
YourClass *another = [[YourClass alloc] init];
another.obj = [obj copyWithZone: zone];
return another;
}
如果它们不同,哪一个更正确? 1. 我在 1st 中与 [self class] 混淆了。我知道目标 c 中的元类,但是在那段代码中有必要吗? 2. copy.name = self.name; vs another.obj = [obj copyWithZone: zone] 与上述有什么区别?
【问题讨论】:
标签: objective-c copy copywithzone