在closure中處理循環(huán)引用

Swift是一們安全的語言,對(duì)于Objective-C中經(jīng)常出現(xiàn)的block引起的循環(huán)引用問題處理的更好,在closure中引用成員屬性的時(shí)候,會(huì)強(qiáng)制使用self,否則編譯不過。如下代碼:

class TestClass {
    var name: String = "aa"
    func viewDidLoad() {
        testEmbededFunction { () -> () in
            name = "bb"
        }
    }

    func testEmbededFunction(f: ()->()) {
        f()
    }
 }

上面的代碼會(huì)出現(xiàn)編譯錯(cuò)誤,提示信息如下:

error.png

蘋果官方解釋如下:

Swift requires you to write self.someProperty or self.someMethod() (rather than just someProperty or someMethod()) whenever you refer to a member of self within a closure. This helps you remember that it's possible to capture self by accident

是因?yàn)閏losure中capture了self,如果self再引用closure的話,就會(huì)導(dǎo)致循環(huán)引用。因此解決循環(huán)引用就有兩種方式:
1、保證closure不會(huì)強(qiáng)引用self
2、保證self不會(huì)強(qiáng)引用closure

第一種情況的解決辦法:
使用capture list來解決[weak self, unowned self]

第二種情況的解決辦法,
在Swift中可以使用@noescape來保證這一點(diǎn),比如這樣定義方法就沒事了:

func testEmbededFunction(@noescape f: ()->()) { 
  f() 
}

官方文檔中對(duì)noescape的描述:

Apply this attribute to a function or method declaration to indicate that a parameter it will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the noescape declaration attribute do not require explicit of self. for properties or method

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

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

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