何时使用主队列

JK1*_*140 2 queue grand-central-dispatch ios swift

我知道UI的任何更新都应该使用以下语法在主队列中运行:

dispatch_async(dispatch_get_main_queue()) {
   UI update code here
}
Run Code Online (Sandbox Code Playgroud)

那些其他案件怎么样?

在我的viewDidLoad()中,我有代码来设置导航栏和工具栏的样式,如下所示:

    let nav = self.navigationController?.navigationBar
    nav?.barStyle = UIBarStyle.Default
    nav?.tintColor = UIColor.blackColor()
    nav?.barTintColor = UIColor(red:133.0/255, green:182.0/255, blue:189.0/255, alpha:1.0)

    let toolBar = self.navigationController?.toolbar
    toolBar?.barTintColor = UIColor(red:231/255, green:111/255, blue:19.0/255, alpha:1.0)
    toolBar?.tintColor = UIColor.blackColor()
Run Code Online (Sandbox Code Playgroud)

我是否应该将此代码包装在主队列中?

在我的tableView cellForRowAtIndexPath函数中,我是否应该包装所有代码以设置主队列中每个表格单元格的UI?

当我提出一个新的模态控制器(self.presentViewController(modalController,animated:true,completion:nil)时,我应该将它包装在主队列中吗?

Ash*_*lls 6

你所有问题的答案都是"不"

除非在文档中指定,否则将在主队列上调用所有UIKit函数.

通常,在使用在后台队列上运行的完成处理程序调用异步func之后,您需要专门在主队列上运行.就像是…

// downloadImage is some func where the 
// completion handler runs on a background queue
downloadImage(completion: { image in  
    DispatchQueue.main.async {
        self.imageView.image = image
    }
})
Run Code Online (Sandbox Code Playgroud)