深层复制 - copyWithZone的这两个实现是不同的?

时间:2013-11-21 06:06:16

标签: objective-c copy copywithzone

我已经看到了两种不同的实现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;
}

如果它们不同,那么它们更正确的是什么?  我在第一节与[自我类]混淆了。我知道目标c中的元类,但是在那段代码中它是否必要?  2. copy.name = self.name; vs another.obj = [obj copyWithZone:zone]   上述之间有什么区别?

1 个答案:

答案 0 :(得分:2)

  1. 弱字符串属性不是一个好主意,它意味着其他人为您的字符串保留强引用,否则它将被取消分配。
  2. 通常,将NSString *属性设为复制属性是个好主意,所以:

    @interface Person : NSObject <NSCopying>
    
    @property (nonatomic,copy) NSString *name;
    
    ...
    
    //and 1st implementation
    @implementation Person
    -(id) copyWithZone:(NSZone *)zone
    {
    Person *copy = [[self class] allocWithZone:zone]; 
    copy.name = self.name; //assigning here is same as coping, should be enough
    

    至于:

    [self class]
    

    在这种情况下返回而不是元类,只是类和此复制调用将是polimorphic并且可以在Person子类中使用。否则copy将始终返回Person,无论子类的方法副本是否被调用都无关紧要。

    copy.name = self.name;
    

    vs

    another.obj = [obj copyWithZone: zone] 
    

    第一种情况是分配给属性 - 它的处理方式取决于属性类型。在复制属性的情况下 - 这两个表达式是相同的。 第二种情况是好的,因为 SomeOtherObject 也实现了深层复制。

    https://developer.apple.com/library/mac/documentation/general/conceptual/devpedia-cocoacore/ObjectCopying.html

相关问题