【问题标题】:Deep copy - are these two implementations of copyWithZone different?深拷贝 - 这两个 copyWithZone 的实现不同吗?
【发布时间】: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


    【解决方案1】:
    1. 弱字符串属性不是一个好主意,这意味着其他人为您的字符串保留了强引用,否则将被释放。

    通常将 NSString * 属性设为 copy 属性是个好主意,因此:

    @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]
    

    在这种情况下,它不是元类返回,只是类,这个复制调用将是多态的,可以在 Person 子类中使用。否则,copy 将始终返回 Person,不管调用哪个子类的方法 copy。

    copy.name = self.name;
    

    对比

    another.obj = [obj copyWithZone: zone] 
    

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

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

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2013-03-14
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2015-08-23
      • 2013-03-19
      相关资源
      最近更新 更多