Reputation: 3581
In one of the tutorial from Ray Wenderlich Series, he used dispatch_get_main_queue()
inside the completion block as follows
func startFiltrationForRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
if let filterOperation = pendingOperations.filtrationsInProgress[indexPath]{
return
}
let filterer = ImageFiltration(photoRecord: photoDetails)
filterer.completionBlock = {
if filterer.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.filtrationsInProgress.removeValueForKey(indexPath)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
pendingOperations.filtrationsInProgress[indexPath] = filterer
pendingOperations.filtrationQueue.addOperation(filterer)
}
Even though he briefly explained why the completion block is required, I was wondering if anyone could answer the following questions
In my own app, I have completion block in quite a lot of place (with reloading table view code in completion block like his. However, I don't not have a single dispatch_get_main_queue code. Does that mean for all UI related task in completion block, I NEED to add dispatch_get_main_queue
?
Upvotes: 1
Views: 430
Reputation: 14504
Yes , you have to use main queue to update tableview. As any UI update should be perform on main thread.
So you must have to reload table on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
// Perform UI operations here
});
It is advisable to perform all calculations, network related functions on secondary thread or background thread, when it comes to perform operation related to UIKit
, then simple switch back to main thread using above mention code.
Upvotes: 2