copyWithZone:(深复制)子类中崩溃
我尝试创建一种符合 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的复制方法时崩溃。
我必须以不同的方式调用该方法吗?
就像 [gene1 copyWithZone:(NSZone *)]
但我必须传递什么对象?我必须创建一个 NSZone 对象吗?或者是否有一个默认值可以作为参数传递?
感谢您的帮助
I try to create a copying method confering to the protocol NSCopying.
I have the following class:
@interface Gene : NSObject <NSCopying>
{
int firstAllele;
int secondAllele;
}
with the method:
-(id) copyWithZone:(NSZone*) zone
{
id clonedGene = [[[self class] allocWithZone:zone] initWithAllele1:first andAllele2:second];
return clonedGene;
}
if I call the method the following way:
Gene* gene1 = [[Gene alloc]initWithAllele1:4 andAllele2:2];
Gene* gene2 = [gene1 copy];
it crashes while calling the copy method of gene1.
do I have to call the method differently?
like [gene1 copyWithZone:(NSZone *)]
but what object will I have to pass? do I have to create an NSZone object? or is there a default one I can pass as argument?
Thank you for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够弄清楚:
我将 Gene 类更改为:
我还需要创建我添加的对象的副本,因此子对象也需要确认复制协议:
所以我还必须
在Allele 类:
由于 allele 是枚举类型,因此不需要实现任何更深层次的复制方法(因为它是基本类型)。
因此,如果我想实现深复制方法,我必须确保所有用作属性的类也实现了复制功能。
谢谢您的帮助,我希望我能回答我自己的问题。
亲切的问候
I was able to figure it out:
I changed the Gene class to:
I needed to also creat copies of the objects i added, so also the sub objects needed to confirm to the copy protocol:
so I had to define also an
Method in the Allele class:
and because allele is of an enumeration type, it doesn't need any deeper copy method implemented (as it is a basic type).
So if I want to implement a deep copy method, I have to make sure that all the classes used as attributes have also a copy function implemented.
Thank you for the help, I hope its ok that I answered my own question.
Kind regards