深入理解object C中复制对象的用法(二)
第五、对象的自定义拷贝
对象拥有复制特性,必须实现NSCopying,NSMutableCopying协议,实现该协议的copyWithZone方法和mutableCopyWithZone方法
深拷贝和浅拷贝的区别就在于copyWithZone方法的实现,
浅拷贝代码如下:
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一个可变对象时,副本对象是不可变的。