Executing on the main thread
suggest changeWhen performing tasks asynchronously, you typically need to ensure a piece of code is run on the main thread. For example, you may want to hit a REST API asynchronously, but put the result in a UILabel. Before updating the UILabel you must ensure that your code is run on the main thread:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Perform expensive tasks
//...
//Now before updating the UI, ensure we are back on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
// label.text = ...
});
});
Whenever you update views on the screen, do so on the main thread. UIKit is not thread-safe, so an update from a background queue can crash or draw incorrectly.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents