OC copy Basic use (deep copy and shallow copy)

Source: Internet
Author: User
Tags file copy

first, what is copy?

Copy literally means "copy", "Copy", which is the process of generating a copy.

Common replication is: file copy, the role is to use a source file to produce a copy file.

Features: 1, modify the contents of the source file, will not affect the copy file;

2. Modify the contents of the copy file without affecting the source file.

The role of copy in OC is to produce a copy object using a source object

Features: 1, modify the properties and behavior of the source object, does not affect the replica object;

2. Modify the properties and behavior of the replica object without affecting the source object.

How do I use the copy feature?

An object can call the copy or Mutablecopy method to create a replica object.

1. Copy: Create an immutable copy (such as NSString, Nsarray, nsdictionary).

2. Mutablecopy: Create a mutable copy (such as nsmutablestring, Nsmutablearray, nsmutabledictionary).

Prerequisites for using the copy feature:

1, copy: Need to abide by nscopying protocol, realize Copywithzone: method.

@protocol nscopying

-(ID) Copywithzone: (Nszone *) zone;

@end

2, Mutablecopy: Need to abide by nsmutablecopying protocol, realize Mutablecopywithzone: Method

@protocol nsmutablecopying

-(ID) Mutablecopywithzone: (Nszone *) zone;

@end

the difference between deep copy and shallow copy:

Deep copy, copy of content, deep copy:

Features: 1, the source object and the replica object are different two objects;

2. The source object reference counter is unchanged, and the replica object counter is 1 (because it is newly generated).

Nature: A new object has been created.

Shallow copy (shallow copy, pointer copy, shallow copy):

Features: 1, the source object and the replica object are the same object;

2. The source object (Replica object) references counter +1, which is equivalent to doing a retain operation.

Essence: No new objects are produced.

Common replication such as:

Only the source object and the replica object are immutable, shallow copy, and the others are deep copy.

Some detailed codes for distinguishing between deep copy and shallow copy are as follows:

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 /** NSMutableString调用mutableCopy : 深复制 */voidmutableStringMutableCopy(){    NSMutableString *srcStr = [NSMutableString stringWithFormat:@"age is %d", 10];    NSMutableString *copyStr = [srcStr mutableCopy];        [copyStr appendString:@"abc"];        NSLog(@"srcStr=%@, copyStr=%@", srcStr, copyStr);}/** NSMutableString调用copy : 深复制 */voidmutableStringCopy(){    NSMutableString *srcStr = [NSMutableString stringWithFormat:@"age is %d", 10];        NSString *copyStr = [srcStr copy];            [srcStr appendString:@"abc"];        NSLog(@"srcStr=%p, copyStr=%p", srcStr, copyStr);}/** NSString调用mutableCopy : 深复制 */voidstringMutableCopy(){    NSString *srcStr = [NSString stringWithFormat:@"age is %d", 10];        NSMutableString *copyStr =  [srcStr mutableCopy];    [copyStr appendString:@"abc"];        NSLog(@"srcStr=%@, copyStr=%@", srcStr, copyStr);}/** NSString调用copy : 浅复制 */void stringCopy(){    //  copy : 产生的肯定是不可变副本        //  如果是不可变对象调用copy方法产出不可变副本,那么不会产生新的对象    NSString *srcStr = [NSString stringWithFormat:@"age is %d", 10];    NSString *copyStr = [srcStr copy];        NSLog(@"%p %p", srcStr, copyStr);}

@property the selection of memory management policies

1. Non-arc

1> copy: only for Nsstring\block;

2> retain: OC object except Nsstring\block;

3> Assign: Basic data type, enumeration, struct (non-OC object), when 2 objects are referenced to each other, one end with retain, one end with assign.

2.ARC

1> copy: only for Nsstring\block;

2> strong: OC object except Nsstring\block;

3> weak: When 2 objects reference each other, one end with strong, one end with weak;

4> Assgin: Basic data type, enumeration, struct body (non-OC object).

--------------------------------------------------------------------------------------------------------------- -----------------------------

Shallow copy : During a copy operation, every layer of replication for the object being copied is a pointer copy.

deep copy : During a copy operation, at least one layer of replication is object replication for the replicated object.

full replication : During a copy operation, every layer of replication for the replicated object is an object copy.

Note: 1, in the copy operation, for the object has n layer is the object copy, we can be called the N-level deep copy, here n should be greater than or equal to 1.

2, for the full replication how to achieve (the current general approach is: Iterative method and archive), where the subsequent addition of depending on the situation,

Do not explain for the time being.

3, the pointer copy commonly known as pointer Copy, object replication is commonly known as content copy.

4, generally speaking,

Shallow copy: Copies a pointer to a reference object.

Deep copy: Copies reference object contents. This definition is blurred when it comes to multi-layer replication.            So the definition of this article does not contradict it. Instead it is a further understanding and explanation of it.

retain: Always shallow copy. The reference count is added one at a time. Returns whether the object is mutable and consistent with the object being copied.

copy: For a deep copy of a mutable object, the reference count does not change, and for an immutable object is a shallow copy,

The reference count is added one at a time. Always returns an immutable object.

mutablecopy: Always deep copy, reference count does not change. Always returns a Mutable object.

Immutable Object : The value changes, and its memory header address changes.

mutable Objects : The first address of the memory does not change, regardless of whether the value changes.

reference count: to give the user a clear idea of how many owners the object has (that is, how many pointers point to the same memory address).

Recently a good friend asked me, when to use the depth of the copy it? Then I will share some of what I have summed up to you, hoping to help you better understand the depth of the copy!

So let's take a look at the conversion of the array type below

1. Immutable objects → conversion of mutable objects:

Nsarray *array1= [Nsarray arraywithobjects:@ "a", @ "B", @ "C", @ "D", nil];

Nsmutablearray *str2=[array1 Mutablecopy];

2. Variable objects → conversion of immutable objects:

Nsmutablearray *array2 = [Nsmutablearray arraywithobjects:@ "AA", @ "BB", @ "CC", @ "DD", nil];

Nsarray *array1=[array2 Copy];

3. Variable object → variable object conversion (different pointer variables point to different memory addresses) :

nsmutablearray *array1= [Nsmutablearray arraywithobjects:@ "a", @ "B", @ "C", @ "D", nil];

Nsmutablearray *str2=[array1 Mutablecopy];

With the two examples above, we can easily convert an object between mutable and immutable, and there is no need to consider the principle of memory usage (that is, the question of reference counting). Yes, that's the charm of a deep copy.

4. Pointer duplication between objects of the same type (different pointer variables point to the same memory address):

A

nsmutablestring *str1=[nsmutablestring stringwithstring:@ "Day"];

Nsmutablestring *str2=[str1 retain];

[str1 release];

B

Nsarray *array1= [Nsarray arraywithobjects:@ "a", @ "B", @ "C", @ "D", nil];

Nsarray *str2=[array1 Copy];

[Array1 release];

In layman's words, when multiple pointers point to the same area of memory, these pointers also have ownership of the memory area . The process of the partition of ownership, when it is necessary to use a shallow copy.

is simplified to:

Q: When do I use a depth copy?

A: A deep copy is used when you want to convert an object from mutable (immutable) to immutable (mutable) or to clone an object's contents;

A shallow copy is used when you want to copy a pointer to an object.

Dear reader Friend, here is the detailed code I used to verify. I hope my friends can find out more about the conclusions I can draw from them. Here are just a few summaries. For any questions about this article please contact me, welcome to point out the shortcomings of this article, thank you!

 #import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {===============                  ============ First Type: Non-container Class immutable object ================== nsstring *[email protected] "one day";        printf ("\ n Initialize assignment reference count is::::%lu", Str1.retaincount);          NSString *strcopy1=[str1 retain];        printf ("\ n continue retain reference count:::%lu", Str1.retaincount);          NSString *strcopy2=[str1 Copy];        printf ("\ n continue copy after reference count is::::%lu", Str1.retaincount);                NSString *strcopy3=[str1 Mutablecopy];                printf ("\ n continue after Mutablecopy:::%lu\n", Str1.retaincount);        printf ("\ n non-container class immutable object \ n Original address:::::::::%p", str1);        printf ("\nretain copy::::::%p", strCopy1);        printf ("\ncopy copy:::::::::%p", strCopy2);    printf ("\nmutablecopy copy:::%p", strCopy3); This indicates that there is no concept of reference count for this type//initialization assignment reference count is: 18446744073709551615//Continue retain reference count is: 18446744073709551615// Continue copy after the reference count is: 18446744073709551615//Continue mutablecopy after: 18446744073709551615 tips: Many people here are said to be assigned, so it's good to explain thisThere is no reference counting concept.         And it can explain why nsstring *strcopy2=[str1 copy];          nsmutablestring *strcopy2=[str1 Copy]; This will not be the reason for the error.         Since it's just a simple assignment, why bother? direct NSString *strcopy2=*str1;         Nsmutablestring *strcopy2=*str1;         In fact, we all see, here is the pointer variable, there is only "copy of the Pointer", and the concept of assignment is completely different, although it looks very similar.  When the type is a string constant, the system optimizes for us, declares multiple strings, but is constant, and the content is equal, then the system only applies a space for us.          Question: Deep copy = shallow copy + assignment?         Assignment process: input data → register processing → open memory → write data.   A deep copy, you can get a copy of the object pointer, and perform an assignment operation. Non-container Class immutable object//original address::::::::: 0x1000033d0//retain Copy:::::::: 0x1000033d0//Shallow copy//copy copy:::::::::: () Tablecopy copy::: 0x10010c420//deep copy printf ("\ n");


============================== Second type: container Class immutable object =================

   Nsarray *array1= [Nsarray arraywithobjects:@ "a", @ "B", @ "C", @ "D", nil];        printf ("\ n Initialize assignment reference count is:::::::::::%lu", Array1.retaincount);          Nsarray *arraycopy1 = [array1 retain];        printf ("\ n continue retain after reference count:::::::::%lu", Array1.retaincount);          Nsarray *arraycopy2 = [array1 copy];        printf ("\ n continue to copy after reference count is::::::::::%lu", Array1.retaincount);          Nsarray *arraycopy3 = [Array1 mutablecopy];            printf ("\ n continue mutablecopy After reference count is::::%lu\n", Array1.retaincount);        printf ("\ n container class non-variable group \ n Original address:::::::::%p\t\t%p", Array1,[array1 objectatindex:1]);        printf ("\nretain copy:::::::%p\t%p", Arraycopy1,[arraycopy1 objectatindex:1]);        printf ("\ncopy Copying:::::::::%p\t%p", Arraycopy2,[arraycopy2 objectatindex:1]);               printf ("\nmutablecopy copy:::%p\t%p", Arraycopy3,[arraycopy3 objectatindex:1]); The initialization assignment reference count is:::::::::::: 1//Continue retain after reference count is::::::::: 2//Continue copy after reference count:::::::: £ º: 3//Continue mutablecopy after reference count is:::: 3//capacity Non-variable group//original address::::::::: 0x10010c6b0 0x100003410//retain Replication:::::::: 0x10010c6b0 0x100003410//Shallow copy//copy copy:::::::::: 0x10010c6b0 0x100003410//Shallow copy Mutablecopy copy::: 0x10010c760 0x100003410//deep copy printf ("\ n");

=============== Third Type: Non-container class variable Object ==================

 Nsmutablestring *str2=[nsmutablestring stringwithstring:@ "Day"];        printf ("\ n Initialize assignment reference count is:::::::::::%lu", Str2.retaincount);          Nsmutablestring *strcpy1=[str2 retain];        printf ("\ n continue retain after reference count:::::::::%lu", Str2.retaincount);          nsmutablestring *strcpy2=[str2 Copy];        printf ("\ n continue to copy after reference count is::::::::::%lu", Str2.retaincount);                Nsmutablestring *STRCPY3=[STR2 Mutablecopy];                printf ("\ n continue mutablecopy After reference count is::::%lu\n", Str2.retaincount);        printf ("\ n non-container class mutable object \ n Original address:::::::::%p", str2);        printf ("\nretin copy::::::%p", strCpy1);        printf ("\ncopy copy:::::::::%p", strCpy2);                 printf ("\nmutablecopy copy:::%p", strCpy3); The initialization assignment reference count is:::::::::::: 1//Continue retain after reference count is::::::::: 2//Continue copy after reference count::.::::::::: The Count is:::: 2//non-container Class mutable object//Original address::: 0x10010c560//retain Copy:::::::: 0x10010c560//Shallow copy//copy System:::::::::: 0x100102720//deep Copy//mutablecopyCopy::: 0x10010c880//deep copy printf ("\ n"); 

========================= Fourth type: container Class variable object ======================

 Nsmutablearray *array2 = [Nsmutablearray arraywithobjects:@ "AA", @ "BB", @ "CC", @ "DD", nil];       printf ("\ n Initialize Assignment reference count::::::::::%lu", Array2.retaincount);         Nsmutablearray *arraycpy1 = [array2 retain];       printf ("\ n continue retain after reference count is:::::::%lu", Array2.retaincount);         Nsmutablearray *arraycpy2=[array2 Copy];       printf ("\ n continue copy after reference count:::::::::%lu", Array2.retaincount);         Nsmutablearray *arraycpy3 = [Array2 mutablecopy];               printf ("\ n continue mutablecopy After reference count is::%lu\n", Array2.retaincount);       printf ("\ n container class variable group \ n Original address:::::::::%p\t%p", Array2,[array2 objectatindex:1]);       printf ("\nretain copy::::::::%p\t%p", Arraycpy1,[arraycpy1 objectatindex:1]);       printf ("\ncopy copy::::::::%p\t%p", Arraycpy2,[arraycpy2 objectatindex:1]);                        printf ("\nnmutablecopy copy:::%p\t%p", Arraycpy3,[arraycpy3 objectatindex:1]);         The initialization assignment reference count is::::-:::::: 1//Continue retain after reference count is::::::: 2//Continue copy after reference count is:::::::: 2//Continue mutablecopy after reference count:: 2 Container class variable group//original address:::::::::-: 0x10010e6c0 0x1000034b0//retain copy:::::::: 0x10010e6c0 0x1000034b0//Shallow copy                     Copy copy::::::::::: 0x10010e790 0x1000034b0//deep copy//nmutablecopy replication::: 0x10010e7c0 0x1000034b0//deep copy } return 0;}

OC copy Basic use (deep copy and shallow 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.