我試圖用閉包實現自定義函數。但它不支持#selector
。#選擇器與閉包不兼容?
下面是一個例子:
class Core: NSObject {
static let shared:Core = Core.init()
func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion:() -> Void) {
button.layer.cornerRadius = button.bounds.width/2
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor = color
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.addTarget(viewController, action: #selector(completion()), for: .touchUpInside)
}
}
Xcode的給了我一個編譯時間問題:
論證 '#selector' 不是指一個 '@objc' 方法,屬性,或初始化程序
使用一個屬性來存儲這樣的完成處理程序是***真***脆弱。它不是線程安全的並且容易出現錯誤 – Alexander
是的,這顯然是對@Mannopson問題的簡單快速回答。針對當前線程的某些手動檢查在多線程情況下會很有用。或者留在主線上,你會沒事的。但對於初學者來說,這將使曼諾普森朝着正確的方向前進。 –
我不同意,這當然不是正確的方向。這是一個危險的方法,可能無法完全理解陷阱的人。如果你真的想要將Crowbar封閉到ObjC API中,那麼我能想到的唯一方法是實例化一個新類,並將封閉體註冊爲具有唯一選擇器的方法。 – Alexander