我通常使用以下代码更新UI更改或弹出一些对话框:
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)%"
}
}
答案 0 :(得分:0)
了解更多信息,请参阅此链接
https://www.hackingwithswift.com/read/9/4/back-to-the-main-thread-dispatch_get_main_queue
答案 1 :(得分:0)
您可以安全地使用此块:
dispatch_async(dispatch_get_main_queue(), ^(){
//Add method, task you want perform on mainQueue
//Control UIView, IBOutlet all here
});
无处不在,闭包和回调函数。它确保其中的代码在主线程上执行。你也可以使用NSOperationQueue.mainQueue.performBlock
,因为它做同样的事情