#import <Foundation/Foundation.h> @interface father:nsobject <NSCopying,NSMutableCopying> @property ( nonatomic,copy) NSString *name; @property (nonatomic,retain) nsnumber *age;-(ID) initwithname: (NSString *) name WithAge :(NSNumber *) age; @end
#import "Father.h" #import "Child.h" @implementation father-(ID) initwithname: (NSString *) name Withage: (NSNumber *) age{ self=[super init]; if (self!=nil) { _name=name; _age=age; } return self;} Shallow copy-(ID) Copywithzone: (Nszone *) zone{ Father *father=[[[self class] allocwithzone:zone] init]; Father.name=_name; Father.age=_age; return father;} Deep copy-(ID) Mutablecopywithzone: (Nszone *) zone{ Father *father=[[[self class] allocwithzone:zone] init]; Father.name=[_name Mutablecopy]; Father.age=[_age copy]; return self;}
NSLog (@ "-------the custom object shallow copy---------"); Shallow copy Learning Father *father=[[father alloc] initwithname:@ "Caitou" Withage:[nsnumber numberwithint:23]; Father *father2=[father Copy]; NSLog (@ "Object address:%p", father); NSLog (@ "Object address:%p", father2); NSLog (@ "object property Address Name:%p", [father name]); NSLog (@ "object property Address Name:%p", [father2 name]); NSLog (@ "Object attribute address age:%p", [Father Age]); NSLog (@ "Object attribute address age:%p", [father2 age]); NSLog (@ "--------the custom object deep copy---------"); Deep copy Father *father4=[[father alloc] initwithname:@ "Caitou" Withage:[nsnumber numberwithint:25]; Father *father3=[father4 Mutablecopy]; NSLog (@ "Object address:%p", father4); NSLog (@ "Object address:%p", Father3); NSLog (@ "object property Address Name:%p", [father4 name]); NSLog (@ "object property Address Name:%p", [father3 name]); NSLog (@ "Object attribute address age:%p", [father4 age]); NSLog (@ "Object attribute address age:%p", [Father3 age]); NSLog (@ "-------shallow copy---------"); Nsarray *array1=[[nsarray Alloc] Initwithobjects:@ "SDF", nil]; Nsarray *array2=[array1 Copy]; NSLog (@ "%p", array1); NSLog (@ "%p", array2); NSLog (@ "-------deep copy---------"); Nsmutablearray *mutablearray=[nsmutablearray arraywithobject:@ "SDFDF"]; Nsmutablearray *mutablearray2=[mutablearray Mutablecopy]; NSLog (@ "%p", Mutablearray); NSLog (@ "%p", mutableArray2); Summary: When copying an immutable object, it is quite retain, that is, the reference count plus one, other cases copy,mutablecopy will allocate space to copy content