Why do we need to call the Main Thread for UI updates?

☆樱花仙子☆ 提交于 2019-12-08 08:24:42

问题


I know that we have to call the main thread when we update the UI. But I can't explain my teammates why we have to do it and why Swift doesn't do it automatically.

They used to call self.present() like this:

self.present(alert, animated: true)

But I know you should call it this way:

DispatchQueue.main.async {
      self.present(alert, animated: true)
}

I actually would like to make sure the method is always called on the main thread but I don't know how... The other question is: Why do I have to make sure this method is called on the main thread and not Swift? There always is an UI update when someone calls this method.

@available(iOS 5.0, *)
open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil)

回答1:


There is a single UI thread in (almost?) every UI framework, and all UI operations have to be performed in this. I think the main reason for this design is to prevent unexpected UI behaviour. Think of the following situation:

  • There is a list of entries in a table, call them "A" and "B"
  • "A" is currently selected
  • The user wants to delete "B"
    • The user selects "B"
    • The user presses a "Delete selected entry" button

If the user where a fast clicker/tapper, and the UI were multithreaded, then it might happen that the "select B" event handler is exectuted after the "delete selected entry" handler. Hence, "A" is still selected and would be deleted.

Therefore, typical frameworks keep track of events in a queue and process this queue in a strict order. This is what you would call "single threaded".

Therefore, if you dispatch something into the main thread, you should be aware that the time of execution is undetermined, so you must not rely on any UI state at the time of enqueuement.



来源:https://stackoverflow.com/questions/53757664/why-do-we-need-to-call-the-main-thread-for-ui-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!