2016-09-06 61 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