1

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?

NSNoob
  • 5,548
  • 6
  • 41
  • 54
user172902
  • 3,541
  • 9
  • 32
  • 75
  • Yes because all of your UI updates should happen on the main thread only. – nishith Singh Sep 06 '16 at 10:40
  • 1
    You only need add it if the block is executing in background thread, example if you using Alamofire the completion block is in main thread already so you don't need it – Tj3n Sep 06 '16 at 10:44
  • Relevant: [Why should UI Changes be performed on Main Queue](http://stackoverflow.com/questions/18467114/why-must-uikit-operations-be-performed-on-the-main-thread) In fact it might be a duplicate but oh well – NSNoob Sep 06 '16 at 10:51
  • Forgot to mention that I have not encountered any problem yet without wrapping code in main queue inside completion block. These mainly includes alamofire and firebase. Thanks Tj3n, I should also check if firebase does it for me already – user172902 Sep 06 '16 at 11:28

1 Answers1

2

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.

technerd
  • 14,144
  • 10
  • 61
  • 92