Reputation: 1452
Let’s say I have a function containing some instructions called in another thread, for example the background thread:
func myFunc(_ completion: @escaping (() -> ())) {
anyActionFromBackgroundThread {
DispatchQueue.main.async {
completion()
}
}
}
Now if I call this function somewhere:
myFunc {
self.tableView.reloadData() // or any UI action
}
By doing this, am I sure that the UI action, here tableView.reloadData()
, will be called from the main thread? Or do I need to add a check in the completion?
Thank you for your help
Upvotes: 2
Views: 940
Reputation: 624
for below iOS10.0, you can use:
func myFunc {
precondition(Thread.isMainThread)
self.tableView.reloadData() // or any UI action
}
Upvotes: 0
Reputation: 437532
Yes, in this particular case you know reloadData
is called from main thread because myFunc
dispatched the call to the completion closure to the main queue. This is the precise reason why myFunc
performed the DispatchQueue.main.async
.
By the way, if you ever want to confirm whether something is running on the main queue, you can add a dispatch precondition:
myFunc {
dispatchPrecondition(condition: .onQueue(.main))
self.tableView.reloadData() // or any UI action
}
This makes your code assumptions explicit, and will help you find any incorrect GCD usage during the development process.
Obviously, in this case you're initiating UI updates, and the main thread checker will help identify misuse. You can find this option on Xcode under “Product” » “Scheme” » “Edit Scheme…” » “Run” » “Diagnostics”.
Upvotes: 5