iOS開發(fā)中__weak和__block修飾符的使用

一. API Reference對(duì)__block變量修飾符有如下幾處解釋:

//A powerful feature of blocks is that they can modify

variables in the same lexical scope. You signal that a block

can modify a variable using the __block storage type

modifier.

//At function level are __block variables. These are mutable

within the block (and the enclosing scope) and are preserved

if any referencing block is copied to the heap.

大概意思?xì)w結(jié)出來就是:

__block對(duì)象在block中是可以被修改、重新賦值的。

二. API Reference對(duì)__weak變量修飾符有如下幾處解釋:

__weak specifies a reference that does not keep the

referenced object alive. A weak reference is set to nil when

there are no strong references to the object.

使用了__weak修飾符的對(duì)象,作用等同于定義為weak的property。自然不會(huì)導(dǎo)致循環(huán)引用問題,因?yàn)樘O果文檔已經(jīng)說的很清楚,當(dāng)原對(duì)象沒有任何強(qiáng)引用的時(shí)候,弱引用指針也會(huì)被設(shè)置為nil。

因此,__block和__weak修飾符的區(qū)別其實(shí)是挺明顯的:

1.__block不管是ARC還是MRC模式下都可以使用,可以修飾對(duì)象,還可以修飾基本數(shù)據(jù)類型。

2.__weak只能在ARC模式下使用,也只能修飾對(duì)象(NSString),不能修飾基本數(shù)據(jù)類型(int)。

3.__block對(duì)象可以在block中被重新賦值,__weak不可以。

4.__block對(duì)象在ARC下可能會(huì)導(dǎo)致循環(huán)引用,非ARC下會(huì)避免循環(huán)引用,__weak只在ARC下使用,可以避免循環(huán)引用。

更多關(guān)于__block變量的詳細(xì)解釋,參見我的另一篇文章,詳細(xì)探討了__block的實(shí)現(xiàn)原理

PS:__unsafe_unretained修飾符可以被視為iOS SDK 4.3以前版本的__weak的替代品,不過不會(huì)被自動(dòng)置空為nil。所以盡可能不要使用這個(gè)修飾符。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容