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)
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With