Question

Has anyone else had this problem? I have a function that depending on situation needs time and sometimes executes very fast. This function is called when a new View Controller is displayed so in order to let the user see that the function is executing I'm using dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ to execute the function in a new thread and at the same time display the new View Controller and Activity Indicator.

It works as I expected but on certain occasions when the function should execute almost instantly it still takes almost 3 sec. before the Activity Indicator disappears and content is displayed. It seems that never mind the situation it always takes the same time (3sec) but when I execute it in main thread there are only limited times when it takes that long.

Was it helpful?

Solution

As omz points out, most UIKit classes are not thread-safe, and anything involving your UI should happen on the main thread. The correct way to do some arbitrarily-long-running thing on another queue while showing an activity indicator looks like this:

[self showProgressUIOrWhatever];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self doSomeWork];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self hideProgressUIOrWhatever];
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top