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

Fantasy picture Fantasy · Nov 19, 2013 · Viewed 28k times · Source

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

Answer

cohen72 picture cohen72 · May 21, 2014

Following the explanation at http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C

"This can be achieved by writing the object and its constituent elements to an archive and then reading back into the new object."

@implementation ClassA

- (id)copyWithZone:(NSZone*)zone{
    NSData *buffer;
    buffer = [NSKeyedArchiver archivedDataWithRootObject:self];
    ClassA *copy = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
    return copy;
}
@end