OC Details-1. Deep copy and shallow copy detailed

Source: Internet
Author: User
Tags shallow copy

Overview

    • Copy: Copy an object with the same content as the source object
    • The following two protocols are required to implement a copy

      • Nscopying
      • Nsmutablecopying
    • Copy returns the type of object

      • Variable, mutablecopy the object returned by the message
      • Immutable, the object returned by the copy message
    • Types of copies

      • Shallow copy, just copy a pointer to the source object, no object created, no memory allocated
      • Deep copy, copy source object, create new object, allocate memory
    • Attention

      • The system has different memory handling for the container class object and the non-container class object, that is, when an object that is not strongly referenced by another object is removed from the container, the object is destroyed
Copy and Retain
    • Copy

      • is to create a new object, a copy of the content
      • Copy represents the same contents as two objects, and the reference count for the new object is 1
      • Irrelevant to the reference count of the old object, there is no change to the object
      • Copy reduces the object-to-context
    • Retain

      • A pointer is created, a copy of the pointer
      • Same object address, same content
      • The reference count of the object +1
Copy behavior of different objects
  • Non-container object ( 如NSString ))

    • For non-mutable objects

      • Rules

        • Copy, shallow copy (pointer copy)
        • Mutablecopy, deep Copy (object copy), return object variable (produce new Mutable object)
      • Example

        - (void) imutableinstancecopy{nsstring *string = @ "Welcome to Xcode"; //copy, Shallow copy nsstring *stringcopy = [string copy]; //mutablecopy, the returned object is variable nsmutablestring *stringmutablecopy = [string mutablecopy]; [Stringmutablecopy appendString:@ "!"]; //string is the same as Stringcopy's memory address NSLog (@ "string:%p", string); NSLog (@ "strongcopy:%p", stringcopy); //string and stringmutablecopy have different memory addresses, allocating a new memory NSLog (@ "stringmcopy:%p", Stringmutablecopy);}   
    • For mutable objects

      • Rules

        • Copy, deep copy (object copy), return object not mutable
        • Mutablecopy, deep Copy (object copy)
      • Example

        - (void) mutableinstancecopy{nsmutablestring *mutablestring = [Nsmutablestring stringwithstring:@ "Welcome to Xcode"];Deep copy, return object not variableNSString *stringcopy = [mutablestringCopy];nsmutablestring *mutablestringcopy = [mutablestringcopy]; //run, this sentence will be an error message, "Attempt to mutate immutable object with appendString:" [mutablestringcopy Appendstring:@ "~ ~ ~"]; //deep copy, return object variable nsmutablestring *stringmutablecopy = [ Mutablestring Mutablecopy]; [Stringmutablecopy appendstring:@ "!"]; //three and mutablestring memory address are different nslog ( @ "mutablestring:%p", mutablestring); nslog (@ "string:%p", stringcopy); nslog (@ "mutablestringcopy:%p", mutablestringcopy); nslog (@ "stringmutblecopy:%p", Stringmutablecopy);}    
  • Container Object ( NSArray )

    • Follow the copy principle for non-container objects
    • Attention

      • The element inside the container is the pointer assignment (shallow copy)
      • Example

        - (void) containerinstanceshallowcopy{Nsarray *array = [Nsarray arraywithobjects:[Nsmutablestring stringwithstring:@ "Welcome"],@ "to",@ "Xcode",NIL];Shallow copyNsarray *arraycopy = [arrayCopy];Deep copyNsmutablearray *arraymutablecopy = [array mutablecopy];NSLog (@ "Array:%p", array);NSLog (@ "arrayCopy:%p", arrayCopy); NSLog (@ "arraymutablecopy:%p", arraymutablecopy); the objects in the container are shallow copies, that is, they have only one copy in memory nsmutablestring *teststring = [array Objectatindex:0]; [teststring appendString:@ "You"]; //Three array contents change NSLog at the same time (@ "array[0]:%@", array[0]); NSLog (@ "arraycopy[0]:%@", arraycopy[0]); NSLog (@ "arraymutablecopy[0]:%@", arraymutablecopy[0]);}        
    • Achieve deep replication in real sense

      - (void) containerinstancedeepcopy{Nsarray *array = [Nsarray arraywithobjects:[Nsmutablestring stringwithstring:@ "Welcome"],@ "to",@ "Xcode",NIL];Object in array is pointer copyNsarray *deepcopyarray = [[Nsarray alloc] Initwitharray:array];True above the deep copy, the object in the array is the object copyNsarray *truedeepcopyarray = [Nskeyedunarchiver unarchiveobjectwithdata:[Nskeyedarchiver Archiveddatawithrootobject:array]];NSLog (@ "Array:%p", array);NSLog (@ "Deepcopyarray:%p", Deepcopyarray); NSLog (@ "Truedeepcopyarray:%p", Truedeepcopyarray); //Change the first element of an array [[[Array Objectatindex:0] appendString:@ "You"]; //affects only the first element of the Deepcopyarray array NSLog (@ "array[0]:%@", array[0]); NSLog (@ "arraycopy[0]:%@", deepcopyarray[0]); //Does not affect the first element of the Truedeepcopyarray array, is the true deep copy NSLog (@ "arraymutablecopy[0]:%@", truedeepcopyarray[ 0]);}                 
  • Custom Objects

    • In defining objects to implement a copy, you need to comply with the nscoping and nsmutablecoping protocols and implement the following methods

      • -(ID) Copywithzone: (Nszone *) zone, variable copy
      • -(ID) Mutablecopywithzone: (Nszone *) zone, non-variable copy
    • Example (copy of custom object person)

      • Compliance protocol, setting member properties

        @interface Person : NSObject <NSCopying, NSMutableCopying>/**姓名*/@property (nonatomic, copy) NSMutableString *name;/**地址*/@property (nonatomic, copy) NSString *address;/**年龄*/@property (nonatomic, assign) NSInteger age;@end
      • Overriding initialization method

         -(instancetype) init{if (self = [super  Init]) {self.name = [[nsmutablestring Alloc] initwithstring:@< Span class= "hljs-string" > "Xiaoyaowang"]; self.address = @ "empty mountain Xinyu after"; self.age = 3;} return self;}        
      • Implementation-(ID) Copywithzone: (Nszone *) zone

         -(id) Copywithzone: (    Nszone *) zone{person *p = [[[self class] allocwithzone:zone] init]; P.name = [self.name copy]; P.address = [self.address Span class= "Hljs-keyword" >copy]; P.age = self.age; return p;}              
      • Implementation-(ID) Mutablecopywithzone: (Nszone *) zone

        - (id)mutableCopyWithZone:(NSZone *)zone{    Person *p = [[[self class] allocWithZone:zone] init];    //注意,此处是mutableCopy方法    p.name = [self.name mutableCopy]; p.address = [self.address copy]; p.age = self.age; return p;}

---restore content ends---

OC Details-1. Deep copy and shallow copy detailed

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.