简体   繁体   中英

Neither weak nor strong or unowned will do during self dismissal?

Is this a valid pattern to avoid being retained after the dismissal?

@objc func backButtonTapped() {
    var s: SiteViewController! = self
    navigationController!.popToRootViewController(animated: true, completion: {
        s.dismissCompletion()
        s = nil // break the strong reference to self
    })
}

You can just use self in the closure. Once control returns from the closure the reference to self will be released.

If you did want to use s there is no reason to declare it as an implicitly unwrapped optional. You could just say var s = self

This closure should release s right once it is executed. I think you can place self there without worries

You can do following to avoid retention,

@objc func backButtonTapped() {
  navigationController!.popToRootViewController(animated: true, completion: { [weak self] in
       if let strongSelf: SiteViewController = self {
         strongSelf.dismissCompletion()
       } 
   })
}

This will make sure there won't be any retention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM