之前写了一篇,emmmmm,其中的观点 我现在觉得有点出入,具体就是 ,先放结论:
iOS中copy≠浅拷贝 mutablecopy≠深拷贝!这一点是一定的!
首先,我之前的结论是mutablecopy生成对象是可变的就是深拷贝,不可变就是浅拷贝,这个只考虑了内存地址的问题,表象看,好像确实是这样,但我忽略了一点!就是容器类型的,比如数组、字典!这个表象看起来是深拷贝,但是其内部的元素并没有进行拷贝,内部元素还是原来的内存地址,即浅拷贝,代码验证:
NSMutableString *muStr = [[NSMutableString alloc]initWithFormat:@"1"]; self.arr = @[muStr,@"2"]; NSMutableArray *muArr = [[NSMutableArray alloc]initWithArray: self.arr]; NSMutableArray *muArr1 = [muArr mutableCopy]; [muStr appendString:@"-"]; NSLog(@"%p %p %p",self.arr,muArr,muArr1); NSLog(@"%p %p %p",self.arr[0],muArr[0],muArr1[0]);
打印:
2018-05-29 17:35:10.424029+0800 copy[13811:5524341] 0x600000429b40 0x600000256aa0 0x6000002566e02018-05-29 17:35:10.424227+0800 copy[13811:5524341] 0x600000256680 0x600000256680 0x600000256680
可以看到,三个数字的第一个元素,确实都是同一个地址!但是其数组的内存地址确实不同了!
这说明了什么???mutableCopy并没有进行元素拷贝啊!我去!
再试下字典:
NSMutableString *muStr = [[NSMutableString alloc]initWithFormat:@"f"]; NSDictionary *dic = @{@"1":muStr}; NSMutableDictionary *mudic = [dic mutableCopy]; [muStr appendString:@"-"]; NSLog(@"%@ %@",dic,mudic);
打印结果:
2018-05-29 17:38:14.863844+0800 copy[13886:5527698] { 1 = "f-";} { 1 = "f-";}
由此 我们看到了!所谓的深拷贝并不是很可靠!并没有进行内部元素的拷贝!那么,怎么真正的进行深拷贝而不是单纯的mutableCopy呢?
首先数组:
我们看到有这个方法:
initWithArray:<#(nonnull NSArray *)#> copyItems:<#(BOOL)#>
我们来试验一下:
NSMutableString *muStr = [[NSMutableString alloc]initWithFormat:@"f"]; self.arr = @[muStr,@"2"]; NSMutableArray *muArr = [[NSMutableArray alloc]initWithArray: self.arr]; NSMutableArray *muArr1 = [[NSMutableArray alloc]initWithArray:muArr copyItems:YES]; [muStr appendString:@"-"]; NSLog(@"%p %p %p",self.arr,muArr,muArr1); NSLog(@"%p %p %p",self.arr[0],muArr[0],muArr1[0]);
打印:
2018-05-29 17:43:09.195246+0800 copy[13999:5532641] 0x604000028c40 0x604000449180 0x604000448dc02018-05-29 17:43:09.195507+0800 copy[13999:5532641] 0x604000448d60 0x604000448d60 0xa000000000000661
变化了!
同理字典也有这个方法:
- (instancetype)initWithDictionary:(NSDictionary*)otherDictionary copyItems:(BOOL)flag;
NSMutableString *muStr = [[NSMutableString alloc]initWithFormat:@"f"]; NSDictionary *dic = @{@"1":muStr}; NSMutableDictionary *mudic = [[NSMutableDictionary alloc] initWithDictionary:dic copyItems:YES]; [muStr appendString:@"-"]; NSLog(@"%@ %@",dic,mudic);
打印结果:
2018-05-29 17:45:40.835326+0800 copy[14057:5535388] { 1 = "f-";} { 1 = f;}
正好符合我们的预测!
以上!