我已经看到了两种实现 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] 和上面的有什么区别?