1,先复习下深copy和浅copy
深拷贝 : 拷贝出来的对象与源对象地址不一致! 这意味着我修改拷贝对象的值对源对象的值没有任何影响,拷贝后的对象的引用计数为1。
浅拷贝 : 拷贝出来的对象与源对象地址一致! 这意味着我修改拷贝对象的值会直接影响到源对象,拷贝后的对象的引用计数加1。
如下图:
2,理解下copy和strong修饰符的区别
属性定义
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *copyedString;
使用代码:
NSMutableString *string = [NSMutableString stringWithFormat:@"aaa"];
self.strongString = string;
self.copyedString = string;
NSLog(@"origin string: %p, %p", string, &string);
NSLog(@"strong string: %p, %p", _strongString, &_strongString);
NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);
self.outputLabel.text = [NSString stringWithFormat:@"origin string:%@\n,strong string:%@\n,copy string %@",string,_strongString,_copyedString];
[string appendString:@"bbb"];
NSLog(@"origin string: %p, %p", string, &string);
NSLog(@"strong string: %p, %p", _strongString, &_strongString);
NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);
由此可见:
使用copy修饰之后,即使属性拷贝来自可变字符串,也会被深拷贝成不可变字符串,也就是源字符串修改之后不会影响到属性字符串,增强了代码的健壮性。
3,那什么情况下copy 和 strong修饰,效果是一样的
NSString *string = [NSString stringWithFormat:@"aaa"];
self.strongString = string;
self.copyedString = string;
NSLog(@"origin string: %p, %p", string, &string);
NSLog(@"strong string: %p, %p", _strongString, &_strongString);
NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);
self.outputLabel.text = [NSString stringWithFormat:@"origin string:%@\n,strong string:%@\n,copy string %@",string,_strongString,_copyedString];
可以看到 如果是不可变拷贝不可变的副本,是不会重新开辟空间。输出就可以看到。3块输出的内存地址是一样的。