Copy reprint in iOS

Source: Internet
Author: User

Summary of COPYHTTP://WWW.JIANSHU.COM/P/5254F1277DBA in iOS reproduced from:
  1. Introducing Copy and Mutablecopy
  2. Introduction to deep copy and shallow copy
  3. Why would block use copy?
  4. Benefits of copy relative to direct assignment
  5. Summarize
Pre-Knowledge:

Memory stack: Automatically allocated by the compiler to release, store the function's parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure.

Heap area of Memory: typically released by programmers, if the programmer does not release, the program may end up being recycled by the OS. Note that it is not the same as the heap in the data structure, but the distribution is similar to the linked list.

Copy method and Mutablecopy method

If you want to create an object that is consistent with the content of the source object, then you can consider copying (copy or mutablecopy), first, I will use three common objects, such as strings, arrays, and dictionaries, to illustrate the difference between copy and mutablecopy.

NSString
NSString *string = @ "Jerry";
[String Copy]--Copy a string of type NSString with Jerry's content
[String mutablecopy]--Copy a string of type nsmutablestring with Jerry's content
Nsdictionary
Nsdictionary *dict = @{@ "name": @ "Jerry"};
[Dict Copy]--Copy a dictionary of nsdictionary types with the same content as Dict
[Dict mutablecopy]--Copy a dictionary of nsmutabledictionary types with the same content as Dict
Nsarray
Nsarray *array = @[@ "Jerry"];
[Array Copy]--copies an array of nsarray types with the same contents as the array
[Array mutablecopy]-copy an array of nsmutablearray types with the same contents as the array
Summarize
  1. Copy-copied object types are always immutable types (for example, NSString, Nsdictionary, Nsarray, and so on)
  2. Mutablecopy the type of object that is copied is always mutable (for example, Nsmutablestring, Nsmutabledictionary, Nsmutablearray, and so on)
Deep copy and shallow copy

What is a deep copy and what is a shallow copy?

Deep copy: The copied object is inconsistent with the source object address! This means that I modify the value of the copied object without any effect on the value of the source object.
Shallow copy: The copied object is the same as the source object address! This means that I modify the value of the copied object to directly affect the source object.

There is a need to correct some of the wrong opinions on the web (below)

Copy is a shallow copy, and mutablecopy are all deep copies.

We know that when we copy an immutable object from a Mutable object using copy, this is a deep copy, not a shallow copy!!

Attention! Deep copy and shallow copy also have relative points!!! Look underneath.

For NSString objects, it is true that deep copies are deep copies, shallow copies are shallow copies, and there is no objection.
But for Nsarray, Nsdictionary, nsset the objects of these container classes? Of course, a shallow copy is still a pointer copy, so does the deep copy mean that it is copied with the object in the container and its container? Or just a container object, just a simple reference to the object inside the container? Here are two things I would call it a incomplete deep copy with a full deep copy.

Incomplete deep copy

A incomplete deep copy is just a copy of the container object (copying a shell), and only one copy of the reference is stored for the object inside the container.


Incomplete deep copy. png

So we know that even if we modify the Copyarray does not affect the source array, but I modify the object in the array by Copyarray, corresponding to the source array of the object will also be modified, you can test themselves.

Full deep copy

A completely deep copy is a complete copy of the object in the container.


Full deep copy. png

It is clear from the picture that, in this case, either modifying the Copyarray or modifying the object in the array by Copyarray will have no effect on the source array.

PS: The default deep copy refers to the incomplete deep copy, if you want to achieve a full deep copy, you have to rewrite the Copywithzone: method, self-realization of full deep copy requirements. The general idea is as follows, in the Copywithzone: the object assignment is not directly assigned value but through the copy method can be achieved,no specific discussion is made here.If a friend asks, then put the sample code on it.
Person.m
-(ID) Copywithzone: (Nszone *) zone
{
Person *cpyperson = [[Person Allocwithzone:zone] init];
Cpyperson.name = Self.name;
Cpyperson.age = Self.age;
return Cpyperson;
}
Nsarray
-(ID) copy
{
Nsarray *cpyarray = [[Nsarray alloc] initwitharray:self Copyitems:yes];
return cpyarray;
}
Main.m
Person *P1 = [[Person alloc] init];
Person *P2 = [[Person alloc] init];
Nsarray *array = @[p1, p2];
Nsarray *cpyarray = [array copy];
NSLog (@ "%@-%@", array, Cpyarray);
Output results
(
"<Person:0x100204af0>",
"<Person:0x100206b20>"
) - (
"<Person:0x100207910>",
"<Person:0x1002074d0>"
)

This makes it possible to complete the deep copy.
PS: Official documentation indicates that the copy method internally calls the Copywithzone method by default, but Nsarray the copy method does not invoke Copywithzone for unknown reasons (perhaps because the concept of zone has been discarded in OC, Apple's official documentation says So here I'm using the taxonomy to rewrite the Nsarray copy method, which is actually not recommended by Apple.

Why does block use copy?

First, block is an object, so block can theoretically be retain/release. However, when the block is created, its memory is allocated on the stack (stack) by default, not on the heap. So its scope is limited to the current context (function, method ...) when it is created, and the program crashes when you call the block outside of the scope.


Apple official documentation

In general, you do not need to call copy or retain a block by yourself. Copy is required only if you need to use it outside of the block definition domain. Copy moves the block from the memory stack to the heap area.

In fact, block using copy is the MRC left behind is a tradition, in the MRC, as mentioned above, in the method block created in the stack, using copy can put him in the heap area, so that in the domain call the block program will not crash. But under the arc, the use of copy and strong are actually the same, because block retain is to use copy to achieve, so block using copy can also install force, indicating that they came from the MRC. Hey

Benefits of copy relative to direct assignment

Look at the following code:


Direct Assignment

Let's guess what the console output is? Is (Kobe), (Kobe, McGrady)?
wrong, WRONG!!!

Array = (
Kobe,
Mcgragy
), Marray = (
Kobe,
Mcgragy
)

Why??? Clearly variable array The object is added after the assignment, why the subsequent addition of the object will also affect the immutable group??
The reason is simple because objective-c supports polymorphism.
So the surface of the Self.array is Nsarray object, in fact, is Nsmutablearray object. This will add a significant cost to post-debug, which can lead to inexplicable errors.
Then look at the following code:
Using copy

Let's guess what the output will be.
That's right!

Array = (
Kobe
), Marray = (
Kobe,
Mcgragy
)

This will ensure that regardless of whether the assignment is variable or non-variable group, Nsarray is Nsarray! (Your father is your father, can not become you) so everyone now know why @property in the NSString, Nsarray, nsdictionary attributes Why most of the time with copy without strong reason?

Here is a diagram to help the novice to understand the difference between copy and mutablecopy, the great god please ignore ^_^


Copy and Mutablecopy

If you can use copy correctly in your project, it will help you with your program. The details determine success or failure!!

Copy reprint in iOS

Related Article

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.