簡體   English   中英

在UIAlertAction的處理程序中,自我應該被捕獲為強者嗎?

[英]Should self be captured as strong in a UIAlertAction's handler?

當寫handler一個封閉UIAlertAction ,應提及self強(默認值), weakunowned

已經有相關與這個主題(帖子1234 ),但老實說,我不認為他們在這種情況下如何幫助。

讓我們關注這個典型的代碼:

func tappedQuitButton() {
    let alert = UIAlertController(title: "Confirm quit", message: nil, preferredStyle: .ActionSheet)

    let quitAction = UIAlertAction(title: "Quit", style: .Default) { (action) in
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    alert.addAction(quitAction)

    let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action) in
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    alert.addAction(cancelAction)

    presentViewController(alert, animated: true, completion: nil)
}

這是UIViewController子類中的一個函數,因此self是顯示警報的視圖控制器。

文件說:

只要該參考可能在其生命中的某個時刻具有“無值”,就使用弱參考來避免參考循環。 如果引用始終具有值,請改用無主引用。

我可能會失明,但我仍然沒有看到這有助於回答我關於UIAlertAction問題。

在上面的代碼中, self 在生命中的某個時刻是否有可能為零? 是。 所以我應該把self標記為weak

但話又說回來,我想不出一個看似合理的場景,當關閉被稱為self時, self將是零。 因此,就封閉而言, self 總會有價值 所以我應該把self標記為unowned

那么,再次,如何在UIAlertAction的處理程序中捕獲self

問自己的關鍵問題是你的警報對象是否由自己“擁有”。 在這種情況下,它不是(因為你在函數體中聲明了let alert = ... )。 因此,您不需要將其創建為弱或無主參考。

如果alert是self的一個屬性,那么它將由self“擁有”,那時你想要在alert“擁有”的閉包中創建一個弱的self引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM