美文网首页
oc中的copy和mutableCopy

oc中的copy和mutableCopy

作者: 我是繁星 | 来源:发表于2018-08-01 14:51 被阅读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方法

    相关文章

      网友评论

          本文标题:oc中的copy和mutableCopy

          本文链接:https://www.haomeiwen.com/subject/wamlvftx.html