我在哪里需要在main_queue上使用dispatch_async?

时间:2016-08-20 14:09:14

标签: swift grand-central-dispatch dispatch-async

我通常使用以下代码更新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)%"
    }
}

2 个答案:

答案 0 :(得分:0)

  1. dispatch_get_main_queue()函数将返回运行UI的主队列。
  2. dispatch_get_main_queue()函数对于更新iOS应用程序的UI非常有用,因为UIKit方法不是线程安全的(除了少数例外),因此您更新UI元素所做的任何调用都必须始终从主队列完成。
  3. 了解更多信息,请参阅此链接

    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,因为它做同样的事情