NSString为什么使用copy修饰

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块输出的内存地址是一样的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值