In my iOS app, I make a lot of web requests. When these requests succeed / fail, a delegate method in the view controller is triggered. The delegate method contains code that is responsible for updating the UI. In the following examples didUpdate(foo:)
is the delegate method, and presentAlert(text:)
is my UI update.
Without DispatchQueue
, the code would like this:
func didUpdate(foo: Foo) {
self.presentAlert(text: foo.text)
}
func presentAlert(text: String) {
let alertController = ...
self.present(alertController, animated: true)
}
When it comes to using DispatchQueue
to make sure my UI will update quickly, I start to lose my ability to tell what's actually happening in the code. Is there any difference between the following two implementations?
First Way:
func didUpdate(foo: Foo) {
self.presentAlert(text: foo.text)
}
func presentAlert(text: String) {
let alertController = ...
DispatchQueue.main.async {
self.present(alertController, animated: true)
}
}
Second way:
func didUpdate(foo: Foo) {
DispatchQueue.main.async {
self.presentAlert(text: foo.text)
}
}
func presentAlert(text: String) {
let alertController = ...
self.present(alertController, animated: true)
}
Does it matter which approach I go with? It seems like having the DispatchQueue block inside of the
presentAlert
function is better, so I don't have to includeDispatchQueue.main.async
any time I want to callpresentAlert
?Is it only necessary to explicitly send a block to the main queue when you (or a framework you are using) has "moved" yourself into a background queue?
If there are any external resources that may help my understanding of GCD, please let me know!