我需要在 main_queue 上的什么地方使用 dispatch_async?

Where do I need to use dispatch_async on main_queue?

我一般用下面的代码来更新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)%"
    }
}
  1. dispatch_get_main_queue() 函数将 return 您的 UI 所在的主队列 运行。
  2. dispatch_get_main_queue() 函数对于更新 iOS 应用程序的 UI 非常有用,因为 UIKit 方法不是线程安全的(有少数例外)所以您为更新 UI 元素所做的任何调用都必须始终从主队列完成。

有关更多信息,请参阅此 link

https://www.hackingwithswift.com/read/9/4/back-to-the-main-thread-dispatch_get_main_queue

您可以安全使用此区块:

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

    });

无处不在,在闭包和回调函数中。它确保其中的代码在主线程上执行。你也可以使用 NSOperationQueue.mainQueue.performBlock 因为它做同样的事情