Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift (Retired) Displaying Our Weather Data Connecting the UI to Our Model

Billy Chan
Billy Chan
4,527 Points

UI Changes - Do we have to use dispatch_async?

Pasan talks about the need to bundle up code related to UI changes and use dispatch_async to insert it into the main queue (the faster lane of the highway)

Is this just a best-practice? What are potential consequences if I don't use dispatch_async and simply insert the UI changes directly into the completionHandler of the downloadTask?

I'm only asking because if there were potential network issues, the UI won't update with the latest weather info anyway, so ensuring the UI receives priority treatment won't really speed up anything.

I guess my question is: Would the user experience be really all that different? Is it imperative we always manage concurrency in such a way (that is, placing priority on UI changes)? Thanks!

Wayne Sang
Wayne Sang
3,157 Points

In my experimentation with this project, I tried doing that and the UI didn't display the new data for about 2 whole seconds. When I implemented the dispatch_async it went to a fraction of a second. And this was with fairly optimal network conditions on first load.

I didn't think the difference would be that significant, and I still don't fully know why it was, but it was a huge difference. You should try it out.

Billy Chan
Billy Chan
4,527 Points

Thanks for the feedback! I tried it out and had similar results. It looks like UI-related code should always be prioritized in the main queue.

1 Answer

If you put the UI updates in the completion handler then each update of a UI component would block operation of your UI while the update occurs. Each UI operation would occur sequentially and could create a bottle neck for your Main UI thread. The UI thread has to remain responsive, otherwise your application might become completely unresponsive and hang. By ensuring that UI updates happen asynchronously you ensure that no blocking (unresponsiveness) occurs while your application performs UI updates. It all happens in the background and your application will not appear to slow or hang up.

Billy Chan
Billy Chan
4,527 Points

Great explanation, thank you very much!