2016-08-20 34 views
0

我一般用下面的代碼更新UI改變或彈出一些對話框:我需要在main_queue上使用dispatch_async?

dispatch_async(dispatch_get_main_queue()) 
{ 
    ... 
} 

我很清楚在下列情況下使用:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    //Add some method process in global queue - normal for data processing 

    dispatch_async(dispatch_get_main_queue(), ^(){ 
    //Add method, task you want perform on mainQueue 
    //Control UIView, IBOutlet all here 

    }); 

//Add some method process in global queue - normal for data processing 

}); 

然而,如何對其他例如,在一些封閉或回調函數中?

autocomplete(sbYouTube.text!) { (results, status) -> Void in 

       if status == "OK" 
       { 
        if let results = results 
        { 
         addAutocompletes(results) 
        } 

        dispatch_async(dispatch_get_main_queue()) 
        { 
         self.tvAutocomplete.reloadData() 
        } 
       } 
       else 
       { 
        NSLog("%@", status) 
       } 
      } 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) 
{ 
    dispatch_async(dispatch_get_main_queue()) 
    { 
     self.downloadedSize = totalBytesWritten 
     self.sizeToDownload = totalBytesExpectedToWrite 

     self.downloadProcess.angle = Double(totalBytesWritten) * 360.0/Double(totalBytesExpectedToWrite) 
     self.lbPercent.text = "\(totalBytesWritten * 100/totalBytesExpectedToWrite)%" 
    } 
} 
+3

您在這裏有什麼問題? –

+0

如果要更新UI,應始終將dispatch_async分配給主隊列。例如,您最後的代碼片段設置了self.lbPercent.text,我們可以推測這是一個UILabel。所以必須在主線上完成。如果您確定自己已經在主線程中,那麼您可以自由地忽略它。 – ncke

回答

0

您是可以放心使用此塊:

dispatch_async(dispatch_get_main_queue(), ^(){ 
    //Add method, task you want perform on mainQueue 
    //Control UIView, IBOutlet all here 

    }); 

無處不在,封鎖和回調函數。它確保其中的代碼在主線程上執行。您也可以使用NSOperationQueue.mainQueue.performBlock,因爲它可以做同樣的事情