ios OC 關鍵字 copy,strong,weak,assign的區別

來源:互聯網
上載者:User

標籤: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的區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.