2016-09-06 51 views
1

tutorial from Ray Wenderlich Series,之一,他用dispatch_get_main_queue()完成块内dispatch_get_main_queue如下我需要在完成块

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) 
} 

即使他简要地解释为什么需要完成块,我想知道是否有人能回答下面的问题

在我自己的应用程序中,我有相当多的地方完成块(重新加载表视图代码在他的完成块中,但是,我没有一个dispatch_get_main_queue代码,这是否意味着对于完成块中的所有UI相关任务,我需要添加dispatch_get_main_queue

+0

是的,因为您的所有UI更新只会在主线程上发生。 –

+1

如果块在后台线程中执行,则只需添加它,例如,如果使用Alamofire,则完成块已在主线程中,因此您不需要它 – Tj3n

+0

相关:[为什么要在主队列上执行UI更改]( http://stackoverflow.com/questions/18467114/why-must-uikit-operations-be-performed-on-the-main-thread)实际上它可能是重复的,但是好吧 – NSNoob

回答

2

是的,你必须使用主队列来更新tableview。因为任何UI更新都应该在主线程上执行。

所以你必须重新加载主线程表。

dispatch_async(dispatch_get_main_queue(), ^{ 

      // Perform UI operations here 
     }); 

可取的做法是执行所有计算,当它涉及使用上面提到的代码以执行涉及UIKit操作,那么简单的开关返回到主线程上辅助线程或后台线程,网络相关的功能。

+1

如果您要将块内的评论更改为'//在这里执行UI操作' – NSNoob

+0

@NSNoob:更新后,请立即检查。感谢您的建议。 – technerd