Explore the deep copy & shallow copy &copy in iOS

Source: Internet
Author: User

What is a deep copy? What is a shallow copy?

Why do you often see the string attribute defined like this, the copy is God horse meaning?

@property (nonatomic,copy) nsstring* name;

Why is the following notation wrong?

@property (nonatomic,copy) nsmutablestring* name;

What is the Copywithzone method for?

Next, we will work together to reveal the answer to the question step-by-step.

What's a copy?

In fact, we really do not need to think of copy too advanced. It is called copy, its ultimate purpose is self-evident, whether we admit it or not, it is the same as CTRL + C and CTRL + V. Copy a copy out so that two objects are not directly affected, completely independent.

Deep copy Shallow copy

There are two types of copy, one of which is variable copy:mutablecopy. The object that you copy with it can change its contents. The other is immutable copy:copy. Use it to copy the object, its contents can not be changed.

Mutablecopy: A variable copy, whose copy process is to re-open an area in memory and copy the object into this area. The new object can be changed, and the change to the new object has no effect on the source object.

Copy: Immutable copy, but also to open up a memory space for new objects, but the new object can not be changed. (Special case: Immutable-"immutable copy, which does not create new memory space.)

(Note: The variable copy and immutable copy here are relative to the class of the foundation framework, if we define a class that implements copy, it is generally mutable).

What does this have to do with deep copies of shallow copies? Let me give you an example and everyone will understand immediately.

Suppose we want to make immutable copy of an immutable object (the original object is immutable and the new object is immutable). So, you know, do we need to create a new memory for the object? Anyway, we can not change this object, then the unified use of one not to it? So, how does the iOS system deal with this problem? Reference counter plus 1 AH. Yes, this is a shallow copy. A deep copy is required to open and close the memory space to the new object.

OK, so let's use a piece of code to illustrate the above problem:

-(void) viewdidload {    [super viewdidload];        Create a mutable string    nsmutablestring* name = [nsmutablestring stringwithformat:@ "Rabbit of Good Dream Garden"];    NSLog (@ "source string:%p-%@", name,name);        Variable-"variable    nsmutablestring* name1 = [name mutablecopy];    [Name1 appendstring:@ "1"];    NSLog (@ "variable string:%p-%@", name1,name1);        Variable-"immutable    nsstring* name2 = [name copy];    NSLog (@ "immutable string:%p-%@", name2,name2);            NSLog (@ "___________ immutable to immutable ______________");    Immutable-"immutable    nsstring* Weibo = @" Rabbit of Good Dream Garden ";    NSLog (@ "source string:%p-%@", Weibo,weibo);    nsstring* Weibo1 = [Weibo copy];    NSLog (@ "new string:%p-%@", Weibo1,weibo1);}

Everyone observes the address of the object in the running result:

 -- ,- the  the: -:12.045Copy of those things [1207:108085] Source string:0X7FEDE25A2F50-Rabbit of the Good Dream garden -- ,- the  the: -:12.046Copy of those things [1207:108085] mutable string:0x7fede25a1690-Good Dream Garden Rabbit 1 -- ,- the  the: -:12.046Copy of those things [1207:108085] Immutable string:0X7FEDE25A1B10-Rabbit of the Good Dream garden -- ,- the  the: -:12.046Copy of those things [1207:108085] ___________ immutable to immutable ______________ -- ,- the  the: -:12.047Copy of those things [1207:108085] Source string:0x10abe2188-Rabbit of the Good Dream garden -- ,- the  the: -:12.047Copy of those things [1207:108085] New string:0x10abe2188-The rabbit of the Good Dream Garden

Copy Property

@property (nonatomic,copy) nsstring* name;

All of us in the beginning of the OC, must have listened to the teacher said such a sentence, when creating attributes, encountered in the string parentheses to write copy. But this is why, I asked the teacher, the teacher said that his teacher said so. Oh, a joke.

Let's just say that the result is that when you assign a value to a property, a copy operation occurs. As for the purpose, you will find the answer next. Nonsense not much to say, on the code:

/* */@interface  student:nsobject@property (nonatomic,copy) nsstring*  Namecopy, @property (nonatomic,strong) nsstring* Namestrong; @end
- (void) viewdidload {[Super viewdidload]; //Create a new variable stringnsmutablestring* name = [Nsmutablestring stringWithFormat:@"Rabbit of the Good Dream garden"]; NSLog (@"source string:%p-%@", Name,name); //Create a Student objectStudent * Student1 =[[Student alloc]init]; Student1.namecopy= name;//Remember that a copy operation occurs at this time because (nonatomic,copy)Student1.namestrong =name; NSLog (@"namecopy:%p-%@", student1.namecopy,student1.namecopy); NSLog (@"namestrong:%p-%@", Student1.namestrong,student1.namestrong); /*through the above code, we find that (nonatomic,copy) modified property, the assignment of a copy operation, opened up a piece of memory to hold the object property (Nonatomic,strong) Assignment, the object properties and the source string shared a piece of memory,     Only reference counter +1 to the source string. */NSLog (@"————————————— The source string changes —————————————————————"); //change the source string to see which namecopy and Namestrong will be affected .[Name setString:@"the string changed."]; NSLog (@"namecopy:%p-%@", student1.namecopy,student1.namecopy); NSLog (@"namestrong:%p-%@", Student1.namestrong,student1.namestrong);}

Operation Result:

 -- ,- the  -: the:07.698Copy of those things [1504:130239] Source string:0x7f830a42fb00-Rabbit of the Good Dream garden -- ,- the  -: the:07.699Copy of those things [1504:130239] Namecopy:0x7f830a42c340-Rabbit of the Good Dream garden -- ,- the  -: the:07.699Copy of those things [1504:130239] Namestrong:0x7f830a42fb00-Rabbit of the Good Dream garden -- ,- the  -: the:07.699Copy of those things [1504:130239] ——————————————————— The source string changes ——————————————————— -- ,- the  -: the:07.699Copy of those things [1504:130239] Namecopy:0x7f830a42c340-Rabbit of the Good Dream garden -- ,- the  -: the:07.700Copy of those things [1504:130239] Namestrong:0x7f830a42fb00-The string changed

Problem:

Is there a problem with the following wording? Why? (The next blog will be the answer for everyone)

@property (nonatomic,copy) nsmutablestring* name;

Custom class Copy

If we want to define our own class, we can use the Copy method, and then we can copy a bunch of objects, how to do it.

Let's say we use copy directly

student* student2 =[student1 copy];

We will find that this time the program will error, saying that we did not implement the Copywithzone method. This means that we can define the copy method for our class, just to do some normative work.

To implement a copy of a custom class:

(1) Comply with the Nscoping Agreement (2) to implement the Copywithzone method. Parameter zone is basically not used, it means specifying that the method allocates memory in one area from beginning to end(all copy will call this method eventually) {method to perform the following actions internally//(1)instantiating an object* a = [a alloc]init]; The general formal notation is [[Self.class alloc] init] because such subclasses can also reuse the method//(2)Assigning a value to a propertya.xx = xx;//(3)return new Objectreturn A; }On the code:
  #import  <foundation/foundation.h> /*   Create a teacher class and have the class implement the Copy method  */ // 1. Compliance with nscopying Protocol   @interface  Teacher:nsobject<nscopying> @property (nonatomic,copy) nsstring  * name;  // 2. Implement Copywithzone method; -(id ) Copywithzone :(nszone *  @end  
  #import  "     @implementation  Span style= "color: #000000;" > Teacher  //  implement Copywithzone method -( Span style= "color: #0000ff;" >id ) Copywithzone: (Nszone *) zone{Teacher  * Teacher = [[Self.class   Alloc]init];    Teacher.name  = Self.name;  return   teacher;}   @end  
  @implementation   Viewcontroller -( void     ) viewdidload {[Super viewdidload];    Teacher  * Teacher = [[Teacher Alloc]init]; Teacher.name  = @ "   " ;        Teacher  * teacher1 = [Teacher copy]; NSLog ( @ " teacher:%p-%@   " ,teacher,teacher.name); NSLog ( @ " teacher1:%p-%@   " ,teacher1,teacher1.name);}  

Operation Result:

----all:07.821 copy of those things [1779:148657 ] Teacher:0x7fd750d13ce0- The rabbit of the Good Dream Garden -: A:07.822 copy of those things [1779:148657] teacher1:0x7fd750d13cf0- Rabbit of the Good Dream Garden

The above is to implement the Copy method with our own class of definitions. So here's a question, can I get my own class implementation mutablecopy? Is there a nsmutablecopying agreement?

Also, in the above code, the addresses of Teacher.name and Teacher1.name are actually the same. Why?

The last answer is relatively simple, I will answer for everyone (Copywithzone method: Tescher.name = self.name)

The other two ask, follow the implementation of copy method to try, also will get the answer soon.

Finish

Explore the deep copy & shallow copy &copy in iOS

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.