深入理解object C中复制对象的用法(二)

第五、对象的自定义拷贝

对象拥有复制特性,必须实现NSCopying,NSMutableCopying协议,实现该协议的copyWithZone方法和mutableCopyWithZone方法

深拷贝和浅拷贝的区别就在于copyWithZone方法的实现,

浅拷贝代码如下:

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCopying>
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)NSString *age;

@end


#import "Person.h"

@implementation Person

- (id)copyWithZone:(NSZone *)zone
{
   //实现自定义浅拷贝
    Person *person=[[self class] allocWithZone:zone];
    person.age=_age;
    person.name=_name;
    return person;
}
@end


main函数为:

    @autoreleasepool {
        
        Person *person=[[Person alloc] init];
        person.name=@"andy";
        person.age=@"20";
        
        Person *person2=[person copy];
        NSLog(@"person 地址为%p,person2地址为%p",person.name,person2.name);
    }

输出结果为:

2013-09-30 17:48:41.007 FDAS[732:303] person 地址为0x1000022c8,person2地址为0x1000022c8


深拷贝代码如下:

- (id)copyWithZone:(NSZone *)zone
{
   //实现自定义浅拷贝
    Person *person=[[self class] allocWithZone:zone];
    person.age=[_age copy];
    person.name=[_age copy];
    return person;
}

结果:

2013-09-30 17:55:13.603 FDAS[742:303] person 地址为0x1000022c8,person2地址为0x1000022e8
        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);


执行结果为:

2013-09-30 18:01:01.394 FDAS[787:303] the dress of arr is 0x100108320 the dress of arr2 is 0x100108320

2013-09-30 18:01:01.396 FDAS[787:303] the retainCount is 2

结果是一样的,是因为Foundation对于不可变复制对象而言,copy方法做了优化,相当于retain,故retaincount变成2.

相当于 在copyWithZone方法中:return [self retain];

第六、copy、mutableCopy和retain之间的关系

在Foundation对象中,copy是一个不可变的对象时,作用相当于retain

当使用mutableCopy时,不管源对象是否可变,副本是可变的,并且实现真正意义上的copy

当我们使用copy一个可变对象时,副本对象是不可变的。


原文地址:https://www.cnblogs.com/riskyer/p/3348029.html