2011-03-26 73 views
2

我尝试创建一个复制方法,该协议符合协议NSCopying。copyWithZone:(深层复制)崩溃的子类

我有以下类:

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

同时调用拷贝崩溃基因的方法1。

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

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

感谢您的帮助

+0

崩溃后的调试器输出是什么? – hoha 2011-03-26 11:22:22

+0

好吧我想通了,我不得不添加一个副本,而不是只传递第一个和第二个等位基因对象: – Aranir 2011-04-05 00:09:11

回答

2

我能弄明白:

我改变了基因类:

@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; 
} 

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

所以,如果我想实现深层复制方法,我必须确保所有用作属性的类都具有实现的复制功能。

谢谢你的帮助,我希望它可以回答我自己的问题。

亲切的问候

+2

你必须去这么长的时间才能使它工作,这表明你没有编写你的'initWithAllele1 :andAllele2:'方法正确。该方法应该“复制”或“保留”传入的等位基因本身。看起来你的内存管理搞砸了。 – 2011-04-05 00:34:33