概念
对象拷贝有两种方式:浅复制和深复制。顾名思义,浅复制,并不拷贝对象本身,仅仅是拷贝指向对象的指针;深复制是直接拷贝整个对象内存到另一块内存中。
简言之:浅复制就是指针拷贝;深复制就是内容拷贝。
String对象的copy与mutableCopy
首先先探究一下复制源为immutable类型的情况下copy与mutableCopy。
NSString *string = @"hello";
NSString *copyString = [string copy];
NSMutableString *mutableString = [string mutableCopy];
NSLog(@"string=%@ address: %p",string,string);
NSLog(@"copystring=%@ address: %p",copyString,copyString);
NSLog(@"mutablestring=%@ address: %p",mutableString,mutableString);
输出结果
MainViewController.m:51 string=hello address: 0x10db47780
MainViewController.m:52 copystring=hello address: 0x10db47780
MainViewController.m:53 mutablestring=hello address: 0x606000101b40
再次探究一下复制源为mutable类型的情况下copy与mutableCopy。
NSMutableString *string = [NSMutableString stringWithString:@"hello"] ;
NSString *copyString = [string copy];
NSMutableString *mutableString = [string mutableCopy];
NSLog(@"string=%@ address: %p",string,string);
NSLog(@"copystring=%@ address: %p",copyString,copyString);
NSLog(@"mutablestring=%@ address: %p",mutableString,mutableString);
输出结果
MainViewController.m:52 string=hello address: 0x606000109fa0
MainViewController.m:53 copystring=hello address: 0xa00006f6c6c65685
MainViewController.m:54 mutablestring=hello address: 0x606000109f40
综上输出结果可以看出:在非集合类对象中:对immutable对象进行copy操作,是指针复制,mutableCopy操作时内容复制;对mutable对象进行copy和mutableCopy都是内容复制。用代码简单表示如下:
[immutableObject copy] // 浅复制
[immutableObject mutableCopy] //深复制
[mutableObject copy] //深复制
[mutableObject mutableCopy] //深复制
集合类的copy与mutableCopy
同理你先看复制源为immutable类型下的copy与mutablecopy。
NSArray *array = @[@"1", @"2"];
NSArray *copyArray = [array copy];
NSMutableArray *mutablecopyArray = [array mutableCopy];
NSLog(@"array address: %p", array);
NSLog(@"copyArrayaddress: %p", copyArray);
NSLog(@"mutablecopyArray address: %p", mutablecopyArray);
输出结果
MainViewController.m:59 array address: 0x6030000cfbb0
MainViewController.m:60 copyArrayaddress: 0x6030000cfbb0
MainViewController.m:61 mutablecopyArray address: 0x604000098350
再来看看复制源为mutable类型下的copy与mutablecopy。
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
NSArray *copyArr = [mutableArray copy];
NSMutableArray *mutablecopyArr = [mutableArray mutableCopy];
NSLog(@"mutableArray address: %p", mutableArray);
NSLog(@"copyArraddress: %p", copyArr);
NSLog(@"mutablecopyArraddress: %p", mutablecopyArr);
输出结果
MainViewController.m:66 mutableArray address: 0x6040000982d0
MainViewController.m:67 copyArraddress: 0x6030000cfb80
MainViewController.m:68 mutablecopyArraddress: 0x604000098290
通过对比输出内存地址可以看出,在集合类对象中,对immutable对象进行copy,是指针复制,mutableCopy是内容复制;对mutable对象进行copy和mutableCopy都是内容复制。但是:集合对象的内容复制仅限于对象本身,对象元素仍然是指针复制。用代码简单表示如下:
[immutableObject copy] // 浅复制
[immutableObject mutableCopy] //单层深复制
[mutableObject copy] //单层深复制
[mutableObject mutableCopy] //单层深复制
参考文档
Apple Collections Programming Topics: Copying Collections