深复制:增加一个指针并且申请一块新的内存,使这个增加的指针指向这个新的内存
浅复制:只是增加了一个指针,指向已经存在的内存。
1.Foundation对于不可变复制对象而言,copy做了优化,相当于retain。
也就是当我们copy的是一个不可变对象时,默认的copy都是浅拷贝,相当于retain
copy优化:在copyWithZone:方法中,return [self tretain];
NSArray *array=[NSArray arrayWithObjects:@"one",@"two",@"three", nil]; NSArray *array1=[array copy]; NSLog(@"array内存地址:%p",array); NSLog(@"array1内存地址:%p",array1); NSLog(@"array的引用计数器:%ld",[array retainCount]);
2016-03-04 13:02:46.494 iOS学习_retain和copy的区别[1999:62514] array内存地址:0x100202010 2016-03-04 13:02:46.495 iOS学习_retain和copy的区别[1999:62514] array1内存地址:0x100202010 2016-03-04 13:02:46.495 iOS学习_retain和copy的区别[1999:62514] array的引用计数器:2
2.对于可变对象而言,copy就是深复制了。
NSMutableArray *mutableArray=[NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil]; NSArray *arrayCopy=[mutableArray copy]; NSLog(@"mutableArray的内存地址:%p",mutableArray); NSLog(@"arrayCopy的内存地址:%p",arrayCopy); NSLog(@"%ld %ld",[mutableArray retainCount],[arrayCopy retainCount]); NSLog(@"%p %p",mutableArray[0],arrayCopy[0]);
2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] mutableArray的内存地址:0x1001023d0 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] arrayCopy的内存地址:0x100102a00 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 1 1 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 0x1000020f8 0x1000020f8
NSArray *arrayA=[NSArray arrayWithObjects:@"1",@"2",@"3",nil]; NSMutableArray *mutableCopyArray=[arrayA mutableCopy]; NSLog(@"%p",arrayA); NSLog(@"%p",mutableCopyArray); NSLog(@"%ld %ld",[arrayA retainCount],[mutableCopyArray retainCount]); NSLog(@"%p %p",arrayA[0],mutableCopyArray[0]);
2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 0x100206cc0 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 0x100206c00 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 1 1 2016-03-04 13:10:44.567 iOS学习_retain和copy的区别[2037:65203] 0x1000020f8 0x1000020f8
有兴趣可以去:http://www.cnblogs.com/csj007523/archive/2012/07/23/2605662.html