Swift closures [weak self] and async tasks

前端 未结 1 858
余生分开走
余生分开走 2020-12-30 07:52

Imagine a situation, when you want to asynchronously load some text from the server and display the result in the ViewController\'s

相关标签:
1条回答
  • 2020-12-30 08:24

    There is no strong reference cycle (retain cycle) here. If you employ a strong reference to self, it is resolved as soon as the dispatch block runs. You theoretically could use strong reference here if you needed to.

    Having said that, I would advise using a weak reference in this case. There's no point in maintaining a strong reference for the duration of the time consuming process solely for the purpose of updating a text field for a view that has already been dismissed. If you were updating other model objects or the like, perhaps you might need to keep the strong reference, but you don't need to do so in this case. As a general principle, one should release memory as soon as reasonably possible.

    Even better, I'd also look at the "long running async operation" and decide whether I really want it to continue to run after the view controller has been dismissed. If not, I'd be inclined to also make the request cancelable and then have deinit cancel the request. And, in that case, you would definitely want to use weak reference (or else deinit wouldn't be called until the long running async operation finishes).

    0 讨论(0)
提交回复
热议问题