Usage of copying objects in IOS and detailed description of deep copy and shortest copy

Source: Internet
Author: User

1. Basic concepts of copying objects

Copy an object as a copy and open up a new memory to store the copy object.

2. To copy an object Protocols and Protocol

Common NSObject objects include NSNumber, NSString, NSArray, NSDictionary, NSMutableArray, NSMutableDictionay, and NSMutableString. objects generated by copy cannot be changed. objects generated by mutableCopy can be changed.

Third, the difference between retain and copy

    @autoreleasepool {        NSMutableArray *array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",nil];        NSMutableArray *retainArray=[array retain];        [retainArray removeLastObject];        for(NSString *str in array)        {            NSLog(@"the part is %@",str);        }        NSLog(@"the retaincount is %ld",[retainArray retainCount]);        // insert code here...        NSLog(@"Hello, World!");            }

Result:

2014-05-19 10:58:22.639 objective[1095:303] the part is one2014-05-19 10:58:22.641 objective[1095:303] the part is two2014-05-19 10:58:22.641 objective[1095:303] the part is three2014-05-19 10:58:22.641 objective[1095:303] the retaincount is 2

NSMutableArray *array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",nil];        NSMutableArray *retainArray=[array mutableCopy];        [retainArray removeLastObject];        for(NSString *str in array)        {            NSLog(@"the part is %@",str);        }        NSLog(@"the retaincount is %ld",[retainArray retainCount]);


Result

10:59:03. 826 objective [110:303] the part is one

10:59:03. 828 objective [110:303] the part is two

10:59:03. 828 objective [110:303] the part is three

10:59:03. 829 objective [110:303] the part is four

10:59:03. 829 objective [110:303] the retaincount is 1


Fourth, differences between COPY and MutableCopy

COPY returns a COPY of an unchangeable object. MutalbeCopy returns a COPY of a mutable object.

        NSArray *array=[NSArray arrayWithObjects:@"one",@"two", nil];        NSMutableArray *array1=[array copy];        [array1 addObject:@"three"];  //error        NSMutableArray *array2=[array mutableCopy];        [array2 addObject:@"three"];  //right        // insert code here...        NSLog(@"Hello, World!");

Fifth, light copy and deep copy

Copy objects as much as possible. The attributes and contained objects in objects are not copied.

Deep COPY Copies all, including the attributes of the object and other objects

The Foundation framework supports replication classes. By default, it is light replication.

NSMutableArray * array = [[NSMutableArray alloc] init]; for (int I = 0; I <3; I ++) {NSObject * obj = [[NSObject alloc] init]; [array addObject: obj]; [obj release];} for (NSObject * obj1 in array) {NSLog (@ "Address: % p, reference count: % ld", obj1, obj1.retainCount);} NSMutableArray * array2 = [array copy]; for (NSObject * obj2 in array2) {NSLog (@ "Address: % p, reference count: % ld", obj2, obj2.retainCount );}

17:28:01. 492 FDAS [681: 303] address: 0x1001081f0, reference count: 12013-09-30 17:28:01. 506 FDAS [681: 303] The address is 0x100108230, and the reference count is 12013-09-30 17:28:01. 506 FDAS [681: 303] The address is 0x100108240, and the reference count is 12013-09-30 17:28:01. 507 FDAS [681: 303] address: 0x1001081f0, reference count: 22013-09-30 17:28:01. 507 FDAS [681: 303] The address is 0x100108230, and the reference count is 22013-09-30 17:28:01. 507 FDAS [681: 303] address: 0x100108240, reference count: 2

5. Custom copying of Objects

The object has the replication feature and must implement the NSCopying and NSMutableCopying protocols to implement the copyWithZone and mutableCopyWithZone methods of the Protocol.

The difference between deep copy and shallow copy lies in the implementation of the copyWithZone method,

The shortest copy code is as follows:

#import 
 
  @interface Person : NSObject
  
   @property(nonatomic,retain)NSString *name;@property(nonatomic,retain)NSString *age;@end
  
 

# Import "Person. h "@ implementation Person-(id) copyWithZone :( NSZone *) zone {// implement custom shallow copy Person * person = [[self class] allocWithZone: zone]; person. age = _ age; person. name = _ name; return person;} @ end

The main function is:
@ Autoreleasepool {Person * person = [[Person alloc] init]; person. name = @ "andy"; person. age = @ "20"; Person * person2 = [person copy]; NSLog (@ "person address: % p, person2 address: % p", person. name, person2.name );}
Output result:

17:48:41. 007 FDAS [732: 303] The person address is 0x000022c8, and the personal 2 address is 0x000022c8.

The deep copy code is as follows:

-(Id) copyWithZone :( NSZone *) zone {// implement custom shallow copy Person * person = [[self class] allocWithZone: zone]; person. age = [_ age copy]; person. name = [_ age copy]; return person ;}

Result:

17:55:13. 603 FDAS [742: 303] The person address is 0x000022c8, and the personal 2 address is 0x000022e8

        NSArray *arr=[NSArray arrayWithObjects:@"one",@"two",nil];        NSArray *arr2=[arr copy];        NSLog(@"the dress of arr is %p the dress of arr2 is %p",arr,arr2);        NSLog(@"the retainCount is %ld",arr.retainCount);

The execution result is:

18:01:01. 394 FDAS [787: 303] the dress of arr is 0x100108320 the dress of arr2 is 0x100108320

18:01:01. 396 FDAS [787: 303] the retainCount is 2


The results are the same because the Foundation optimizes the copy method for immutable copy objects, which is equivalent to retain. Therefore, retaincount is changed to 2.

Return [self retain] In the copyWithZone method;

6. Relationship between copy, mutableCopy, and retain

In the Foundation object, when copy is an immutable object, the function is equivalent to retain.

When mutableCopy is used, no matter whether the source object is variable or not, the copy is variable, and the true copy is implemented.

When we use copy as a mutable object, the copy object is immutable.


Deep copy and shallow copy:

1. Shallow copy:

    Car *car=[[[self class] allocWithZone:zone] init];    car.engine=_engine;    car.name=_name;    car.weight=_weight;    return car;

Test code:

Car * car = [[Car alloc] init]; Engine * engine = [[Engine alloc] init]; car. engine = engine; [engine release]; // NSLog (@ "engine retaincount is % lu", [engine retainCount]); car. name = @ "Audi"; car. weight = @ 1000; Car * car2 = [car copy]; // NSLog (@ "car2 retaincount is % lu", [car2 retainCount]); NSLog (@ "car % @, car2: % @", car. engine, car2.engine );

Output result:

Car , Car2:

It can be seen that the shallow replication only copies the pointer and does not create a new memory space.

2. Deep copy:

-(Id) copyWithZone :( NSZone *) zone {/*** shortest copy **/Car * car = [[[self class] allocWithZone: zone] init]; engine * engineCopy = [[_ engine copy] autorelease]; car. engine = engineCopy; NSString * namecopy = [[_ name copy] autorelease]; car. name = namecopy; NSNumber * weightcopy = [[_ weight copy] autorelease]; car. weight = weightcopy; return car ;}

Test code:

Car * car = [[Car alloc] init]; Engine * engine = [[Engine alloc] init]; car. engine = engine; [engine release]; // NSLog (@ "engine retaincount is % lu", [engine retainCount]); car. name = @ "Audi"; car. weight = @ 1000; Car * car2 = [car copy]; // NSLog (@ "car2 retaincount is % lu", [car2 retainCount]); NSLog (@ "car % @, car2: % @", car. engine, car2.engine );

Result:

Car , Car2:

New space is opened up, and zone represents a piece of memory space.

 Car *car=[[[self class] allocWithZone:zone] init];


Note that the above Code uses [self class] instead of car, because if car is used, the car subclass will encounter memory problems when calling this method to implement the copy protocol.

In addition, when a subclass inherits the parent class, it inherits all attributes of the parent class, including the Protocol to be implemented.

Third, NSFoundation, when we copy an immutable object, the default copy is a shortest copy, which is equivalent to retain

        NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil];        NSArray *array1 = [array copy];        NSLog(@"%p",array);        NSLog(@"%p",array1);        NSLog(@"the retaincount is %lu",[array retainCount]);

Output result:

CopyDemo1 [673: 303] 0x10010a5d0

20:01:10. 969 copyDemo1 [673: 303] 0x10010a5d0

20:01:10. 969 copyDemo1 [673: 303] the retaincount is 2

Note that retaincount will increase

When mutableCopy is used, deep copy is implemented regardless of whether the object is variable or not.

        NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil];        NSMutableArray *array1 = [array mutableCopy];        NSLog(@"%p",array);        NSLog(@"%p",array1);        NSLog(@"the retaincount is %lu",[array retainCount]);

Result:

CopyDemo1 [695: 303] 0x10010a5d0

20:07:08. 570 copyDemo1 [695: 303] 0x10010b260

20:07:08. 570 copyDemo1 [695: 303] the retaincount is 1

Fourth, retain is equivalent to two objects pointing to the same pointer.

        NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:@"one",@"two",@"three",@"foure", nil];        NSMutableArray *array2 = [array1 retain];        [array2 removeLastObject];        NSLog(@"%@",array1);        NSLog(@"the retaincount is %ld",array2.retainCount);
Result:

2013-12-28 20:13:02.915 copyDemo1[736:303] (    one,    two,    three)2013-12-28 20:13:02.917 copyDemo1[736:303] the retaincount is 2







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.