简体   繁体   English

DispatchQueue.main.async 的初学者问题

[英]Beginner question on DispatchQueue.main.async

In MainViewController , in viewDidLoad() I'm calling a function which in turn tests if Auth.auth().currentUser == nil;MainViewController ,在viewDidLoad()我调用了一个函数,该函数反过来测试Auth.auth().currentUser == nil; If the condition is met then the statement to execute presents another view controller.如果满足条件,则要执行语句会显示另一个视图控制器。

In the if statement, why does the statement to execute need to be preceded by DispatchQueue.main.async (if I don't write DispatchQueue.main.async then the view controller doesn't present and it's just stuck on MainViewController ).在 if 语句中,为什么要执行语句前面需要DispatchQueue.main.async (如果我不写DispatchQueue.main.async则视图控制器不存在,它只是卡在MainViewController )。

Because at the time viewDidLoad is called your view controller has not yet been added to the view hierarchy.因为在调用viewDidLoad ,您的视图控制器尚未添加到视图层次结构中。 A view controller that is not part of the view hierarchy can't present another view controller.不属于视图层次结构的视图控制器不能呈现另一个视图控制器。 You should get a log message in the console saying something similar to that when you try to present the other view controller without async dispatch.当您尝试在没有异步调度的情况下呈现其他视图控制器时,您应该在控制台中收到一条日志消息,内容类似于该消息。

Putting the call in the DispatchQueue.main.async causes the presentation to be delayed until the next runloop cycle which happens to be enough that your view controller has been added to the view hierarchy once it gets called.将调用放入DispatchQueue.main.async会导致演示文稿延迟到下一个 runloop 循环,这恰好足以让您的视图控制器在被调用后已添加到视图层次结构中。

A better solution would be to put your current user check in a more appropriate place, possibly viewDidAppear .更好的解决方案是将您当前的用户检查放在更合适的位置,可能是viewDidAppear

Dispatch.main.async is used for reason being that all the UI related have to be performed on the mainQueue.使用 Dispatch.main.async 的原因是所有相关的 UI 都必须在 mainQueue 上执行。 Since UIViewController presentation is a UI task, hence performed on mainQueue由于 UIViewController 呈现是一个 UI 任务,因此在 mainQueue 上执行

Also, to answer why it's not presenting when Dispatch.main is not used is perhaps you are doing it on a thread which isn't main.另外,要回答为什么在不使用 Dispatch.main 时它不显示的原因可能是您在不是主要的线程上执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM