3 回答
TA贡献1780条经验 获得超5个赞
[unowned self]
示例:发出异步网络请求
self
何时使用 unowned self
或 weak self
[unowned self]
[weak self]
[unowned self]
[weak self]
特别是在视频的例子中
TempNotifier
onChange
self
unowned
self
差异 unowned
和 weak
unowned
weak
weak
unowned
weak
unowned
unowned
TA贡献1712条经验 获得超3个赞
如果您有一个闭包来处理来自网络请求的响应,请使用 weak
因为他们活得很久。视图控制器可以在请求完成之前关闭 self
在调用闭包时不再指向有效对象。 如果有处理按钮上的事件的闭包。这可能是 unowned
因为一旦视图控制器消失,按钮和它可能引用的任何其他项就会从 self
同时离开。封闭区也会同时消失。 class MyViewController: UIViewController { @IBOutlet weak var myButton: UIButton! let networkManager = NetworkManager() let buttonPressClosure: () -> Void // closure must be held in this class. override func viewDidLoad() { // use unowned here buttonPressClosure = { [unowned self] in self.changeDisplayViewMode() // won't happen after vc closes. } // use weak here networkManager.fetch(query: query) { [weak self] (results, error) in self?.updateUI() // could be called any time after vc closes } } @IBAction func buttonPress(self: Any) { buttonPressClosure() } // rest of class below. }
- 3 回答
- 0 关注
- 631 浏览
添加回答
举报