Fantasy Fantasy - 6 months ago 45
Objective-C Question

How can I make a deep copy in Objective-C?

I'm learning ios develop now and I'm confused with deep copy.
For example,I have three class below. Now I want to deep copy ClassA, can anybody teach me to finish the copy method?

A:

@interface ClassA : NSObject <NSCopying>

@property (nonatomic, assign) int aInt;
@property (nonatomic, retain) ClassB *bClass;

@end


B:

@interface ClassB : NSObject <NSCopying>

@property (nonatomic, assign) int bInt;
@property (nonatomic, retain) ClassC *cClass;

@end


C:

@interface ClassC : NSObject <NSCopying>

@property (nonatomic, assign) int cInt;
@property (nonatomic, copy) NSString *str;

@end

Answer

You should add the copyWithZone: method in each class you want to be copiable.

NB: I wrote this by hand, watch out for typos.

-(id) copyWithZone:(NSZone *) zone
{
    ClassA *object = [super copyWithZone:zone];
    object.aInt = self.aInt;
    object.bClass = [self.bClass copyWithZone:zone];
    return object;
}

-(id) copyWithZone:(NSZone *) zone
{
    ClassB *object = [super copyWithZone:zone];
    object.bInt = self.bInt;
    object.cClass = [self.cClass copyWithZone:zone];
    return object;
}

-(id) copyWithZone:(NSZone *) zone
{
    ClassC *object = [super copyWithZone:zone];
    object.cInt = self.cInt;
    object.str = [self.str copy];
    return object;
}