SickAustrian SickAustrian - 3 months ago 17
Swift Question

When to use threading for UI updates in SWIFT

I am confused about when to put code that updates the UI on the main queue:

dispatch_async( dispatch_get_main_queue() )
{
// Do UI update here
}


Online sources such as https://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1 suggest to use that approach. However, many swift/iOS tutorials do not apply that coding pattern, especially when it comes to small UI updates such as
button.hidden = false
or
button.backgroundColor = UIColor.blueColor()
.

Answer

All UI elements should be update in the main thread of the application. It is an golden rule if you would like to see proper transitions and smoothly updated ui.

If you are working on the main thread there is no need to use :

dispatch_async( dispatch_get_main_queue() )
{
     // Do UI update here
}

because you are in the main thread of the application.

You need to use code block that you present in the situation when you are working on another thread or in another operation and you need to update UI in these threads.

So imagine situation you need to do some calculation in the background thread and update UI in this thread.

Code solution example:

//Async operation in with we would like to do some calculation and do not block main thread of the application.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
       let result = doSomeCalculation()
       //After we receive result of the calculation we need to update UI element `UIlable` so we call main thread for that.
       dispatch_async(dispatch_get_main_queue()) {
                label.stringValue = result
       }
}