iOS - When to Call the User Interface Changing Functions in the Main Wire

advertisements

Every time I make an API call to my server to get data, I already know that I have to use the following block to execute UI changing commands because my API call executes in the background thread:

dispatch_async(dispatch_get_main_queue(), ^{
    //do UI stuff
});

However, what if I have a function that does UI changing stuff outside of the API call block? For example:

-(void)doALotOfUIChanging
{
    //do a lot of UI changing
}

In my API call block, do I need to call that UI changing function in the main thread like so?:

[apiObject getDataFromObject:my.Object successCallback:^(Array *data)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self doALotOfUIChanging];
    });
}
errorCallback:^(NSString *error)
{
    NSLog(@"%@", error);
}];

Or do I not have to call it in the main thread since the function is already outside of the API call block like so?:

[apiObject getDataFromObject:my.Object successCallback:^(Array *data)
{
    [self doALotOfUIChanging];
}
errorCallback:^(NSString *error)
{
    NSLog(@"%@", error);
}];

I also have functions that perform segues to other view controllers, so I'm also wondering if I should call them in the main thread as well. I'm doing some code clean up and I don't want to have to constantly rewrite the dispatch_async function in situations that I might not have to, so any help or advice would be greatly appreciated. Thanks.


Short answer: Yes you should update your UI on main thread.

Threads and Your User Interface

If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but even for those that do not, keeping this behavior on the main thread has the advantage of simplifying the logic for managing your user interface.

There are a few notable exceptions where it is advantageous to perform graphical operations from other threads. For example, you can use secondary threads to create and process images and perform other image-related calculations. Using secondary threads for these operations can greatly increase performance. If you are not sure about a particular graphical operation though, plan on doing it from your main thread.

Reference:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html