copyWithZone: (deep copy) crash in subclass

4k Views Asked by At

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

1

There are 1 best solutions below

1
On

I was able to figure it out:

I changed the Gene class to:

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

I needed to also creat copies of the objects i added, so also the sub objects needed to confirm to the copy protocol:

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

so I had to define also an

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

Method in the Allele class:

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

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