Imagine a situation, when you want to asynchronously load some text from the server and display the result in the ViewController's
UITextField
.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//... some long running async operation
if let textResponse = responseFromServer {
dispatch_async(dispatch_get_main_queue(), { [weak self] () in
self?.textField.text = textResponse
})
}
})
A.) Do I need to use [weak self] within the closure used for async calls?
I thought I need to, but I am not sure after I read some Q/A here at StackOverflow and went through quite a few open source apps that don't use [weak self] for async tasks + closures.
i.e.:
The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. (Shall we always use [unowned self] inside closure in Swift)
There is no strong reference cycle in my case.
or:
But to be clear, it would still be best to use a strong reference in this circumstance. (Swift ARC and blocks)
B.) Let's say it's good to go with the strong reference. What happens to the ViewController when the user navigates to the different page in the middle of async loading? Would it keep the invisible ViewController in the app memory until the async task finishes?