How can I make a deep copy in Objective-C?
deep-copy, objective-c
Solution
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;
}
Problem
I'm learning ios development and I'm confused with deep copying in Objective-C. 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 ```