iOS-copy strong 可变 不可变 深浅拷贝

2018-07-04  本文已影响14人  我是谁重要吗

NSString内存分配情况

可变 不可变:

NSString 不可变是说它指向的不可变,重新赋值NSString 是重新指向了新的地址,之前指向的地址内容不发生改变。

NSMutableString *strM1 = [[NSMutableString alloc] initWithString:@"123"];
NSMutableString *strM2 = [[NSMutableString alloc] initWithString:@"123"];
NSLog(@"strM1地址:%p",strM1); //strM1地址:0x60000024f750
NSLog(@"strM2地址:%p",strM2); //strM2地址:0x60000024fbd0
NSLog(@"%d %d %d",strM1 == strM2,[strM1 isEqual:strM2],[strM1 isEqualToString:strM2]); //0 1 1
[strM1 appendString:@"456"];
NSLog(@"strM1地址:%p",strM1); //strM1地址:0x60000024f750

strM1 改变了值,但指向的地址没有改变 。因为strM1是可变的NSMutableString

深浅拷贝:

NSString中

NSSMutableString中

以下原理相同
NSArray;
NSMutableArray;
NS;
NSMutable
;

copy 、mutableCopy

copy 、mutableCopy和深浅拷贝没有直接对应关系

copy,strong

copy,strong和深浅拷贝没有完全对应关系
简单来说,希望不跟着源头改变,就用copy,跟着改变就用strong

参考:
https://www.zybuluo.com/MicroCai/note/50592
NSString与NSMutableString的深浅拷贝
NSString什么时候用copy,什么时候用strong
https://www.jianshu.com/p/6419828ae238
https://www.jianshu.com/p/b7de4031838a

上一篇 下一篇

猜你喜欢

热点阅读