【问题标题】:copyWithZone: (deep copy) crash in subclasscopyWithZone:(深拷贝)在子类中崩溃
【发布时间】:2023-04-09 04:01:01
【问题描述】:

我尝试创建一个赋予协议 NSCopying 的复制方法。

我有以下课程:

@interface Gene : NSObject <NSCopying>
{

    int firstAllele;
    int secondAllele;

}

用方法:

-(id) copyWithZone:(NSZone*) zone
{
    id clonedGene = [[[self class] allocWithZone:zone] initWithAllele1:first andAllele2:second];

    return clonedGene;
}

如果我按以下方式调用该方法:

Gene* gene1 = [[Gene alloc]initWithAllele1:4 andAllele2:2];
Gene* gene2 = [gene1 copy];

调用gene1的copy方法时崩溃。

我必须以不同的方式调用该方法吗?

喜欢[gene1 copyWithZone:(NSZone *)],但我必须通过什么对象?我必须创建一个 NSZone 对象吗?还是有一个我可以作为参数传递的默认值?

感谢您的帮助

【问题讨论】:

  • 崩溃后的调试器输出是什么?
  • 好吧,我想通了,我必须添加一个副本,而不是只传递第一个和第二个等位基因对象:

标签: objective-c deep-copy copywithzone


【解决方案1】:

我想通了:

我将 Gene 类更改为:

@interface Gene : NSObject 
{
    Allele * first;
    Allele * second;   
}

我还需要创建我添加的对象的副本,因此还需要确认复制协议的子对象:

-(id) copyWithZone:(NSZone*) zone  
{  
    id clonedGene = [[[self class] allocWithZone:zone] initWithAllele1:[first copy] andAllele2:[second copy]];   
    return clonedGene;  
}

所以我还必须定义一个

-(id) copyWithZone:(NSZone*) zone;

等位基因类中的方法:

-(id) copyWithZone:(NSZone*) zone  
{  
    id copiedAllele = [[[self class] allocWithZone:zone] initWithAllele:allele];    
    return copiedAllele;  
}

并且由于等位基因是枚举类型,因此不需要实现任何更深层次的复制方法(因为它是基本类型)。

所以如果我想实现一个深拷贝方法,我必须确保所有用作属性的类也实现了一个拷贝功能。

感谢您的帮助,我希望我能回答我自己的问题。

亲切的问候

【讨论】:

  • 您必须竭尽全力才能使其正常工作,这表明您没有正确编写 initWithAllele1:andAllele2: 方法。该方法应该 copyretain 传入的等位基因本身。看起来你的内存管理搞砸了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 2015-01-13
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多