我一般用下面的代碼更新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)%"
}
}
您在這裏有什麼問題? –
如果要更新UI,應始終將dispatch_async分配給主隊列。例如,您最後的代碼片段設置了self.lbPercent.text,我們可以推測這是一個UILabel。所以必須在主線上完成。如果您確定自己已經在主線程中,那麼您可以自由地忽略它。 – ncke