NSString,NSMutableString使用retain, copy理解

原帖作者:LIN1986LIN

原帖地址:点击打开链接

一直以为copy就是深拷贝,会产生一个新的对象,指针和内容都是新的,retain只是引用计数+1。

今天测试代码的时候发现一个问题,再经仔细一测,才发现不是这么回事.

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int main(int argc, charchar *argv[])  
  2. {  
  3.     NSString *str = @"google";  
  4.     NSString *strRetain = [str retain];  
  5.     NSString *strCopy = [str copy];  
  6.     NSMutableString *strMutCopy = [str mutableCopy];  
  7.       
  8.     NSLog(@"str        = %p,    retainCount = %d", str, [str retainCount]);  
  9.     NSLog(@"strRetain  = %p,    retainCount = %d", strRetain, [strRetain retainCount]);  
  10.     NSLog(@"strCopy    = %p,    retainCount = %d", strCopy, [strCopy retainCount]);  
  11.     NSLog(@"strMutCopy = %p,     retainCount = %d", strMutCopy, [strMutCopy retainCount]);  
  12.      
  13. }  

output:


 

 观察打印信息可以发现,不管是retain还是copy对于NSString来说都是浅拷贝,还是指向的之前的内存区域。retainCount=-1是因为str为字符串常量,系统会用UINT_MAX来标记,系统不收回,也不做引用计数。
NSString 应用 retain 还是 copy?

1。对NSString应用retain,效率无疑是最好的

2。用copy最安全,因为NSString 为 NSMutableString 的基类,如果将NSMutableString 以retain的形式赋值给NSString后,后续修改NSMutableString会导致NSString内容的变化,这通常不是我们希望的,所以用copy最安全。

参考文档 NSCopying Protocol Reference

Your options for implementing this protocol are as follows:

  • Implement NSCopying using alloc and init... in classes that don’t inherit copyWithZone:.
  • Implement NSCopying by invoking the superclass’s copyWithZone: when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject function, make explicit assignments to pointer instance variables for retained objects.
  • Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值