oc中的copy和mutableCopy

2018-08-01  本文已影响0人  我是繁星
今天有空深入分析一下copy和mutableCopy这两个方法

首先用四种情况作了一下测试:

    NSString * str = @"";
    NSMutableString * mutableStr = [[NSMutableString alloc]initWithString:@""];
    NSString * copyStr = [str copy];
    NSMutableString * MutableCopyStr = [str mutableCopy];
    NSMutableString * mutableCopyMutableStr = [mutableStr mutableCopy];
    NSString * copyMutableString = [mutableStr copy];
    NSLog(@"\nstr: %p 类型:%@\nmutableStr: %p 类型:%@\ncopyStr: %p 类型:%@\nMutableCopyStr: %p 类型:%@\nmutableCopyMutableStr:%p 类型:%@\ncopyMutableString:%p 类型:%@",str,[str class],mutableStr,[mutableStr class],copyStr,[copyStr class],MutableCopyStr,[MutableCopyStr class],mutableCopyMutableStr,[mutableCopyMutableStr class],copyMutableString,[copyMutableString class]);

打印结果如下:(__NSCFConstantString代表不可变,__NSCFString代表可变)

str:                  0x105e9e068 类型:__NSCFConstantString
mutableStr:           0x604000245e80 类型:__NSCFString
copyStr:              0x105e9e068 类型:__NSCFConstantString
MutableCopyStr:       0x6040002461b0 类型:__NSCFString
mutableCopyMutableStr:0x6040002460c0 类型:__NSCFString
copyMutableString:    0x1077ee038 类型:__NSCFConstantString
NSString NSMutableString
Copy 浅拷贝,NSString类型 深拷贝,NSString类型
MutableCopy 深拷贝 ,NSMutableString类型 深拷贝 NSMutableString类型

可以看到除了copyStr = [str copy]以外都生成了新对象,也就是说只有不可变对象copy的时候是浅拷贝,其他情况都是深拷贝,
what?不是说copy都是深拷贝吗??
其实也不难理解,因为不可变类型本身不可改变,因为不可变所以不存在一个对象改变另一个也改变的情况,所以做深拷贝纯属浪费内存。。

总结:copy方法返回的对象类型是由方法本身决定的,copy返回对象一定是不可变的,mutableCopy返回的一定是可变的,只有不可变对象copy的时候是浅拷贝,其余都是深拷贝

最后注意如果自定义类,想要实现copy要实现copyWithZone方法

上一篇 下一篇

猜你喜欢

热点阅读