Objective-c copy object
There are two types of object replication: Deep replication and shallow replication. It sounds very difficult, but it is actually very simple;
For example:
NSMutableArray * array1 = [NSMutableArray arrayWithObjects:@"a" ,@"b", nil]; NSMutableArray *array2 = array1; [array2 addObject:@"c"]; for(NSString *s in array1) { NSLog(@"%@",s); }
Output result:
2014-08-16 11:17:21.524 text[1679:303] a2014-08-16 11:17:21.526 text[1679:303] b2014-08-16 11:17:21.526 text[1679:303] c
As shown in the preceding figure, we add "c" to array2, but there are also times of array1 (there must be c in array2 );
This is a light copy. We copied the pointer of array array1 to array2. Suppose that array1 points to the oxfffff area. Now we assign the address that array2 = array1 points to array2, when we operate on array2, it is actually the region of the operation, and array1 points to that region, so this result will appear;
This is light replication;
Deep replication:
In the above example, if you want to modify array2, and array1 remains unchanged, you need to use deep replication. Deep Replication involves both variable replication and immutable replication, which means that the copy body can be changed, just as nsarray is immutable and nsmutablearry is variable. The copy and mutablecopy methods are required;
For classes provided by the system, such as NSArray and NSString, you can directly use the copy and mutablecopy methods;
If it is a self-created class, we need to implement proxy
The
-(Id) copyWithZone :( NSZone *) zone
-(Id) mutableCopyWithZone :( NSZone *) zone
Method. One is immutable replication, and the other is mutable replication;
Implementation Method:
-(id)copyWithZone:(NSZone *)zone{ first *new = [[first allocWithZone:zone]init]; new.string = self.string; return new;}-(id) mutableCopyWithZone:(NSZone *)zone{ first *new = [[first allocWithZone:zone]init]; new.string = self.string; return new;}
Let's take a look at the code to understand what deep replication means. Deep replication re-creates a space and initializes it with the original value;
That's it;