Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 358
Godlike Avatar asked Dec 10 '22 04:12

Godlike


1 Answers

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.

like image 91
Andreas Oetjen Avatar answered Dec 29 '22 03:12

Andreas Oetjen