IOS deep replication and light Replication
Sample Code for copying:
NSMutableArray *mArray = [NSMutableArray arrayWithObjects: [NSMutableString stringWithString: @"origionA"], [NSMutableString stringWithString: @"origionB"], [NSMutableString stringWithString: @"origionC"], nil]; NSMutableArray *mArrayCopy = [mArray mutableCopy]; NSMutableString *string = [mArray objectAtIndex:0]; [string appendString:@"Append"]; [mArrayCopy removeObjectAtIndex:1]; NSLog(@"object.name = %@",mArray); NSLog(@"object.name = %@",mArrayCopy);
Print result:
15:18:15. 151 AppTest [14507: 122304] object. name = (
OrigionAAppend,
OrigionB,
OrigionC
)
15:18:15. 151 AppTest [14507: 122304] object. name = (
OrigionAAppend,
OrigionC
)
Note:
The Foundation class implements the methods named copy and mutableCopy. You can use these methods to create a copy of an object and Protocol (the following code) to complete this work, if you must distinguish whether the object to be generated is a mutable copy or an immutable copy, then pass Protocol to generate immutable copies, through Protocol to generate a mutable copy.
However, the copy and mutableCopy methods of the Foundation class are only a new reference to the object by default. They all point to the same memory, that is, the shallow copy. Therefore, the above result is displayed.
@protocol NSCopying- (id)copyWithZone:(NSZone *)zone;@end@protocol NSMutableCopying- (id)mutableCopyWithZone:(NSZone *)zone;@end
Sample Code for deep replication:
@interface DemoObject : NSObject
@property (strong, nonatomic) NSString *name;@end@implementation DemoObject- (id)copyWithZone:(NSZone *)zone{ DemoObject* object = [[[self class] allocWithZone:zone]init]; return object; }@end
NSMutableArray *mArray = [NSMutableArray arrayWithObjects: [NSMutableString stringWithString: @"origionA"], [NSMutableString stringWithString: @"origionB"], [NSMutableString stringWithString: @"origionC"], nil]; NSMutableArray *mArrayCopy = [mArray mutableCopy]; NSMutableString *string = [mArray objectAtIndex:0]; [string appendString:@"Append"]; [mArrayCopy removeObjectAtIndex:1]; NSLog(@"object.name = %@",mArray); NSLog(@"object.name = %@",mArrayCopy);
Print result:
15:18:15. 150 AppTest [14507: 122304] object. name = object
15:18:15. 151 AppTest [14507: 122304] newObject. name = newObject
Note:
Must be implemented in the Custom class Or Protocol and implementation of copyWithZone: Or mutableCopyWithZone: method, in order to respond to the copy and mutableCopy methods to copy objects.
The parameter zone is related to different buckets. You can allocate and use these buckets in programs, these zones need to be processed only when you write applications that need to allocate a large amount of memory and want to optimize the memory allocation by grouping the space into these buckets. You can use the value passed to copyWithZone: and pass it to the memory allocation method named allocWithZone. This method allocates memory in the specified storage area.