Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 859
Fantasy Avatar asked Nov 19 '13 13:11

Fantasy


People also ask

How do I copy an object in Objective C?

<NSCopying> Protocol and copyWithZone Method Implementation Now when executed, the above code creates a copy of the object referenced by account1 and assigns a pointer to the new object to variable account2.

Does object assign do a deep copy?

Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.

Does copy () create a deep copy?

Making Deep Copies By the way, you can also create shallow copies using a function in the copy module. The copy. copy() function creates shallow copies of objects.


2 Answers

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 
like image 180
cohen72 Avatar answered Sep 24 '22 09:09

cohen72


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; } 
like image 33
James Webster Avatar answered Sep 21 '22 09:09

James Webster