码迷,mamicode.com
首页 > 移动开发 > 详细

ios OC 关键字 copy,strong,weak,assign的区别

时间:2018-05-17 15:23:11      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:count   code   内存地址   ssi   ios   sign   其他   ret   影响   

 

一、先介绍 copy、strong、weak 的区别,如代码所示

@property(copy,nonatomic)NSMutableString*aCopyMStr; 
@property(strong,nonatomic)NSMutableString*strongMStr; 
@property(weak,nonatomic)NSMutableString*weakMStr; 
@property(assign,nonatomic)NSMutableString*assignMStr; 

NSMutableString *mstrOrigin = [[NSMutableStringalloc] initWithString:@"mstrOriginValue"]; 

self.aCopyMStr= mstrOrigin; 
self.strongMStr= mstrOrigin; 
self.weakMStr= mstrOrigin; 
NSLog(@"mstrOrigin输出:%p,%@\\n", mstrOrigin,mstrOrigin); NSLog(@"aCopyMStr输出:%p,%@\\n",_aCopyMStr,_aCopyMStr); 
NSLog(@"strongMStr输出:%p,%@\\n",_strongMStr,_strongMStr); 
NSLog(@"weakMStr输出:%p,%@\\n",_weakMStr,_weakMStr); 
NSLog(@"引用计数%@",[mstrOriginvalueForKey:@"retainCount"]); //输出结果 

//2016-09-01 15:19:13.134 lbCopy[1205:87583] mstrOrigin输出:0x7892a5e0,mstrOriginValue 
//2016-09-01 15:19:13.135 lbCopy[1205:87583] aCopyMStr输出:0x7893deb0,mstrOriginValue 
//2016-09-01 15:19:13.135 lbCopy[1205:87583] strongMStr输出:0x7892a5e0,mstrOriginValue 
//2016-09-01 15:19:13.135 lbCopy[1205:87583] weakMStr输出:0x7892a5e0,mstrOriginValue 
//2016-09-01 15:19:13.135 lbCopy[1205:87583] 引用计数2

 

结论:

1、copy 和 strong 引用计数器加一,weak 引用计数器不加一。

2、strong 和 weak 的内存地址都指向 mstrOrigin,copy 为创建新的内存地址并复制内容,再指向 mstrOrigin。

 

二、修改 mstrOrigin 的值的时候,必然不会影响aCopyMStr,只会影响strongMStr和weakMStr

三、将 mstrOrigin 置为 nil,strong 和 weak 都为 nil,copy 不为 nil

 

四、assign

assign 引用计数器不加一,但是要为指向的置为空时,只是进行值释放。这就导致野指针存在,即当这块地址还没写上其他值前,能输出正常值,但一旦重新写上数据,该指针随时可能没有值,造成奔溃。

 

ios OC 关键字 copy,strong,weak,assign的区别

标签:count   code   内存地址   ssi   ios   sign   其他   ret   影响   

原文地址:https://www.cnblogs.com/shen5214444887/p/9050780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!