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:
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;
For a self-created class, we need to implement the proxy <nscopying>
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;