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

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

猜你喜欢

转载自www.cnblogs.com/shen5214444887/p/9050780.html
今日推荐