iOS开发中,对象拥有复制特性,必须实现NSCopying,NSMutableCopying协议,实现该协议的copyWithZone方法和mutableCopyWithZone方法
深拷贝和浅拷贝的区别就在于copyWithZone方法的实现,
浅拷贝代码如下:
?
1 2 3 4 5 6 7 8 |
#import <foundation foundation.h="">
@interface Person : NSObject<nscopying> @property(nonatomic,retain)NSString *name; @property(nonatomic,retain)NSString *age;
@end </nscopying></foundation> |
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#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函数为:
?
1 2 3 4 5 6 7 8 9 |
@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); } |
输出结果为:
?
1 |
2013-09-30 17:48:41.007 FDAS[732:303] person 地址为0x1000022c8,person2地址为0x1000022c8 |
深拷贝代码如下:
?
1 2 3 4 5 6 7 8 |
- (id)copyWithZone:(NSZone *)zone { //实现自定义浅拷贝 Person *person=[[self class] allocWithZone:zone]; person.age=[_age copy]; person.name=[_age copy]; return person; } |
结果:
?
1 |
2013-09-30 17:55:13.603 FDAS[742:303] person 地址为0x1000022c8,person2地址为0x1000022e8 |
?
1 2 3 4 |
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); |
执行结果为:
2015-09-30 18:01:01.394 FDAS[787:303] the dress of arr is 0x100108320 the dress of arr2 is 0x100108320
2015-09-30 18:01:01.396 FDAS[787:303] the retainCount is 2
结果是一样的,是因为Foundation对于不可变复制对象而言,copy方法做了优化,相当于retain,故retaincount变成2.
相当于 在copyWithZone方法中:return [self retain];
欢迎大家批评指正~