[問答專欄] All func pointers need a protocol now

文章題目:All func pointers need a protocol now
作者:pmst(1345614869)
微博:PPPPPPMST

正文

問題鏈接

問題描述

Gargoyle 想實現一個對象之間的回調,但是卻未使用 protocol + delegate 的設計模式,而是使用了如下方法:

final class MyView: UIView {  
    var onSomeAction: ((String) -> Void)!  
}  
  
final class MyViewController: UIViewController {  
    let myView = MyView(frame: CGRectZero)  
    override func viewDidLoad() {  
        super.viewDidLoad()  
        myView.onSomeAction = someFunc  
    }  
  
    private func someFunc(str: String) {  
    }  
}  

注意到 myViewController 實例與 myView 實例會形成一個 retain cycle ,倘若你想為 var onSomeAction 使用 weak 關鍵字,抱歉!報錯“weak cannot be applied to non-class type xxxx” ,顯然對于非 class 對象你無法使用 weak 關鍵字。

問題解答

Jessy 提供了一種解決方案:

var onSomeAction_get: () -> (String -> Void)! = {nil} 

myView.onSomeAction_get = {[unowned self] in self.someFunc} 

首先對閉包類型進行了修改,從(String) -> Void 變為 () -> (String -> Void) ;其次為 myViewonSomeAction_get 賦值是用閉包方式,其中使用了[unowned self] 保證不會形成retain cycle,這也是問題解決的關鍵所在。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容