I was wondering, during UI updating, is there ever be a chance, that the UI is destroy, or no longer valid?
If the view controller in question has been dismissed, the view will be removed from the view hierarchy. But, the way you’ve written this, if the view controller has been dismissed, your code will update a view that isn’t visible any more. Worse, the memory associated with your view controller and its views be not deallocated until this dispatched block finishes. There’s no point in doing that.
So, if we were to use your code pattern, you might instead do:
@IBAction func buttonClick(_ sender: Any) {
recordLabel.text = "Perform some time consuming networking..."
let workItem = DispatchWorkItem { // use `[weak self] in` pattern here, too, if you reference `self` anywhere
// Perform some time consuming networking...
DispatchQueue.main.async { [weak self] in
// Update the view if it’s still around, but don’t if not
self?.recordLabel.text = "Done"
}
}
DispatchQueue.global().async(execute: workItem)
}
Or, more naturally,
@IBAction func buttonClick(_ sender: Any) {
recordLabel.text = "Perform some time consuming networking..."
DispatchQueue.global().async { // use `[weak self] in` pattern here, too, if you reference `self` anywhere
// Perform some time consuming networking...
DispatchQueue.main.async { [weak self] in
// Update the view if it’s still around, but don’t if not
self?.recordLabel.text = "Done"
}
}
}
It is worth noting that one generally doesn’t dispatch network requests to a global queue because networking libraries like URLSession
, Alamofire, etc., already perform their request asynchronously. So you wouldn’t do that async
dispatch to the global queue.
Likewise, if this network request was merely to update something for this view controller’s view, you might even cancel the network request when the view was dismissed. (Why bother continuing to do a network request merely to update a view that might no longer exist?) It depends upon the nature of the request.
Finally, when you get this immediate issue behind you, you might reconsider whether the view controller should be issuing network requests at all, as opposed to some other type of object. That’s well beyond the scope of this question, but something to reconsider in the long term.
But we can’t comment further on any of these observations without seeing what you’re doing inside this dispatch to the global queue.