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
<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.
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.
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.
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
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With