Objective-c deep copy and shallow copy

Source: Internet
Author: User

Deep copy and shallow copy shallow copy
    • Shallow copy (shallow copy) feature: The referenced object is not copied, its newly copied object is just a pointer to an existing reference object. (It's actually the equivalent of a shortcut copy under Windows System)
      Here is a simple example to separate the deep copy with the shallow copy:
//Create two variable stringsnsmutablestring*student = [[nsmutablestringAlloc] initwithstring:@"Zhangsan"];nsmutablestring*anotherstu= [[nsmutablestringAlloc] initwithstring:@"LiSi"];//Use two variable strings to create an array, i.e. there are two elements in the group whose element type is a mutable string        Nsarray*students = @[student,anotherstu];//Assign a copy of the created array to another array        Nsarray*copystu = [students copy];//Print the original array and copy the contents of the resulting array        NSLog(@"Before moidfy the students:%@ and copystu:%@", Students,copystu);//Modify the value of the first element of the resulting array after copying[copystu[0] appendstring:@"-teacherzhang"];//Print the values of the original array to see if any changes have occurred        NSLog(@"After modify copystu:the students info:%@", students);

The results are printed before moidfy the students: (
Zhangsan,
LiSi
) and Copystu: (
Zhangsan,
LiSi
)
After modify copystu:the students info: (
"Zhangsan-teacherzhang",
LiSi
)
This is a shallow copy, just a copy of a pointer, and does not copy a complete object.

Deep copy
    • Deep copy

Features: The true meaning of the replication concept. The result is multiple, not just an object reference. (a full copy of the object, including the methods therein)

#import <Foundation/Foundation.h> intMainintargcConst Char* argv[]) {@autoreleasepool {//Defines an immutable string        NSString*STR = @"Hello";//Print out the address of STR        NSLog(@"Str ' s address:%p", str);//The immutable string can be converted to a mutable string by the Mutablecopy protocol        nsmutablestring*ANOTHERSTR = [Str mutablecopy];NSLog(@"Anotherstr ' s address:%p", ANOTHERSTR); [Anotherstr appendstring:@"Qingyun"];NSLog(@"anotherstring:%@", ANOTHERSTR);nsmutablestring*MSTR = [[nsmutablestringAlloc] initwithstring:@"HELLO"];NSLog(@"Mstr ' s address:%p", MSTR);//You can convert a mutable string to an immutable string by using the Copy protocol        nsmutablestring*ANOTHERMSTR = [MSTR copy];NSLog(@"Anothermstr ' s address:%p", ANOTHERMSTR); [Anothermstr appendstring:@"-qingyun"]; }return 0;}
Copy of Custom Objects

The prerequisite for implementing a copy of a custom object is that the protocol must be implemented, otherwise a crash occurs when a custom object invokes a Copy object.
Example to illustrate this problem, create a Qycar class to inherit from NSObject, and follow the Nscopying protocol to implement a copy of the custom object in MAIN.M

In the Qycar header file, the code is as follows:

#import <Foundation/Foundation.h>@interface QYCar : NSObject <NSCopying>@property (nonatomicstrong)NSString *name;@property (nonatomicassign)NSInteger year;@end

The code in QYCAR.M is as follows:

#import "QYCar.h"  @implementation qycar //out-of-the-box initialization mode-(Instancetype) init{ Self= [SuperINIT];if( Self) { Self. Name= @"BWM"; Self. Year= -; }return  Self;} - (NSString*) description{return[NSStringstringwithformat:@"Name:%@,year:%ld", Self. Name, Self. Year];} - (ID) Copywithzone: (Nszone *) zone{Qycar *carcopy; Carcopy = [Qycar allocwithzone:Nil]; Carcopy. Name= Self. Name; Carcopy. Year= Self. Year;returnCarcopy;}@end

Set up an object car in main.m, and invoke the out-of-the-box initialization method, and then create a new object carcopy, and copy the contents of car to carcopy, in order to show that we have successfully copied car, change the Carcopy Name property, and hit Print it out and show us this is a deep copy.

int  Main (int  argc, const  char  *        Argv[] {@autoreleasepool {qycar *car = [[Qycar alloc] init]; nslog         (@ "car:%@" , car);        Qycar *carcopy = [car copy];        Carcopy.name  = @ "Henancar" ; nslog         (@ "carcopy:%@" , carcopy); nslog      (@ "car again:%@" , car);     } return  0 ;} 

The result of the output is:
2015-07-01 21:06:43.302 selfwithcopy[2631:2055248] car:name:bwm,year:2013
2015-07-01 21:06:43.303 selfwithcopy[2631:2055248] carcopy:name:henancar,year:2013
2015-07-01 21:06:43.303 selfwithcopy[2631:2055248] Car again:name:bwm,year:2013

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Objective-c deep copy and shallow copy

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.