Shall we always use [unowned self] inside closure in Swift

前端 未结 9 2142
耶瑟儿~
耶瑟儿~ 2020-11-22 05:22

In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide

\"enter

9条回答
  •  借酒劲吻你
    2020-11-22 05:39

    I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

    • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
    • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

      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.
       }
      

提交回复
热议问题