Reputation: 2198
UI changes should be made on the main thread. If not, it can lead to wrong behavior, warnings or crashes (and sometimes it still works like expected though).
Anyway, I've started to wrap almost any UI changes in dispatch_async(dispatch_get_main_queue)) { ... }
. Recently I just wondered whether this could be best practice to do so with all UI related stuff, so every single presentViewController
, dismissViewController
etc., because the code gets just overflowed by hundreds of those wraps.
Of course, sometimes it is obvious that it wouldn't be needed; e.g. when a user has tapped a button that leads to some immediate UI changes. But there are methods that get called in different contexts, where you should probably ensure it by just wrap it preventively. In the end I've started implementing those everywhere because otherwise you have to be really careful not to misjudge or forget one where needed.
What is your approach?
Upvotes: 2
Views: 185
Reputation: 80273
I think you should explicitly call UI changes on the main thread each time, but only if necessary.
Rationale: you only need to specify the main thread if you are not already on the main thread. For example, in a UIViewController
subclass where you implement methods like viewDidLoad
, or table view datasource
methods, you can assume that you are on the main thread already. Thus, to wrap UI statements here into additional async
blocks is redundant and produces cluttered and unnecessarily verbose code.
If, on the other hand, you are in some background thread, you should make it explicit that you are doing something on the main thread. This will add clarity and enhance readability and maintainability.
Upvotes: 4