Shallow copy and deep copy

Source: Internet
Author: User

The difference between copy and retain:

1, copy is to create a new object, retain is to create a pointer, reference object Count plus one. 2. The Copy property identifies two objects with the same contents, the new object retain count is 1, has nothing to do with the old object reference count, and the old object does not change. 3. Copy reduces the dependency of the object on the context.

In the actual development, it is found that the nature of the problem is the same address, is a shallow copy, the address is a deep copy.

During iOS development, it is generally differentiated into two concepts: object and container, the copy of the object is a shallow copy, and the mutablecopy is a deep copy. The container also refers to the method above, but remember that a copy of the container's containing object, whether using copy or Mutablecopy, will be a shallow copy. To implement a deep copy of an object, you must provide a copy of the method yourself.

Copy construction:

not that all objects support copy, and Mutablecopy methods, must support Nscoding, nsmutalbecopying protocol, can be. This section is usually written on your own for custom objects. If you want to customize copy then you must obey Nscopying and implement Copywithzone: method, if you want to customize mutablecopy then you must obey Nsmutablecopying, and implement Mutablecopywithzone: Method

Example: Custom Objects

@interfaceMyobj:nsobject<nscopying,nsmutablecopying>{nsmutablestring*name; NSString*Imutablestr; intAge ;} @property (nonatomic, retain) nsmutablestring*Name: @property (nonatomic, retain) nsstring*Imutablestr, @property (nonatomic)intAge ;@end@implementationMYOBJ@synthesizename;@synthesizeAge ;@synthesizeImutablestr;- (ID) init{if(self =[Super Init]) {Self.name=[[Nsmutablestring alloc]init]; Self.imutablestr=[[NSString Alloc]init]; Age= -1; }       returnSelf ;}- (void) dealloc{[name release];       [Imutablestr release]; [Super Dealloc];}- (ID) Copywithzone: (Nszone *) zone{MYOBJ*copy = [[Selfclass] [allocwithzone:zone] init]; Copy->name =[name copy]; Copy->imutablestr =[imutablestr copy];//copy->name = [name Copywithzone:zone];;//copy->imutablestr = [name Copywithzone:zone];//Copy->age =Age ; returncopy;}- (ID) Mutablecopywithzone: (Nszone *) zone{MYOBJ*copy = Nscopyobject (self,0, zone); Copy->name =[Self.name mutablecopy]; Copy->age =Age ; returncopy;}@end

Shallow copy

A shallow copy is a copy of the memory address, so that the target object pointer and source object point to the same piece of memory space.

A shallow copy is simply a simple copy of the object, allowing several objects to share a piece of memory, and when the memory is destroyed, several pointers to the memory need to be redefined before they can be used, or they will become wild pointers.

A shallow copy inside IOS:

In IOS, using the Retain keyword for reference counting is a more insured, shallow copy. He allows a few pointers to share the same memory space, but also in release due to the existence of the count, will not be easy to destroy the memory, to achieve a more simple use.

Deep copy:

Deep copy refers to the specific contents of the Copy object, and the memory address is self-allocated, after the end of the copy, two objects, although the value is the same, but the memory address is not the same, two objects do not affect each other, non-interference.

Deep copy in iOS:

iOS provides copy and Mutablecopy methods, as the name implies, copy is copying a Imutable object, and Mutablecopy is copying a mutable object. Here are a few examples to illustrate.

1. Non-Container class objects of the system
this refers to objects such as Nsstring,nsnumber and so on.
nsstring *string = @ "Origion";
nsstring *stringcopy = [string copy];
nsmutablestring *stringmcopy = [string mutablecopy];
[stringmcopy appendstring:@ "!!"];
view memory you can see that string and stringcopy point to the same chunk of memory (also known as Apple weak reference weak reference), at which point the reference count for Stringcopy is as much as 2 for string ( note here , because the @ "Origion" object is a constant data segment, not an object on the heap, so string and stringcopy are actually pointing to a non-heap object whose reference count should be-1, which can be verified by the program. The reference count we call is actually the object used to manage the application on the heap. ). And Stringmcopy is what we call the true meaning of replication, the system allocates new memory to it, but the pointer points to the same string as it refers to. let's look at the following example:
nsmutablestring *string = [nsmutablestring stringwithstring: @ "origion"];
nsstring *stringcopy = [string copy];
nsmutablestring *mstringcopy = [string copy];
nsmutablestring *stringmcopy = [string mutablecopy];
[mstringcopy appendstring:@ "MM"];//error
[String appendstring:@ "origion!"];
[stringmcopy appendstring:@ "!!"];
The memory allocated by the above four NSString objects is not the same. But for Mstringcopy is actually a imutable object, so the above will be an error.
for non-container class objects of the system, we can assume that if copying an immutable object, copy is pointer copy (shallow copy) and mutablecopy is the object copy (deep copy). If it is a copy of a mutable object, it is a deep copy, but the object returned by copy is immutable.  2. System's container class object
refers to nsarray,nsdictionary and so on. For the container class itself, the conclusions discussed above are also applicable, and it is necessary to explore the changes of objects in the container after replication.
//copy Returns an immutable object, Mutablecopy returns a Mutable object
Nsarray *array1 = [Nsarray arraywithobjects:@ "a", @ "B", @ "C", nil];
Nsarray *arraycopy1 = [array1 copy];
//arraycopy1 is the same Nsarray object as the array (pointing to the same object), including the elements inside the array that also point to the same pointer
NSLog (@ "Array1 retain count:%d", [array1 Retaincount]);
NSLog (@ "Array1 retain count:%d", [arrayCopy1 Retaincount]);
Nsmutablearray *marraycopy1 = [Array1 mutablecopy];
//marraycopy1 is a mutable copy of Array1, which points to different objects and array1, but the elements in them and the elements in the array1 point to the same object. MArrayCopy1 can also modify their own objects
[MArrayCopy1 addobject:@ "de"];
[MArrayCopy1 removeobjectatindex:0];
array1 and ArrayCopy1 are pointer copies, and MARRAYCOPY1 is an object copy, and mArrayCopy1 can also change elements in the period: delete or Add. Note, however, that the element content inside the container is a pointer copy. Let's test it with another example.
Nsarray *marray1 = [Nsarray arraywithobjects:[nsmutablestring stringwithstring:@ "A"],@ "B", @ "C", nil];
Nsarray *marraycopy2 = [mArray1 copy];
NSLog (@ "MArray1 retain count:%d", [MArray1 Retaincount]);
Nsmutablearray *marraymcopy1 = [MArray1 mutablecopy];
NSLog (@ "MArray1 retain count:%d", [MArray1 Retaincount]);
//marraycopy2,marraymcopy1 and MArray1 point to different objects, but the elements are the same object--the same pointer

Shallow copy and deep copy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.