Ash
Ash

Reputation: 2304

iOS UIView is not updated immediately

When I do UI updates from the main thread, they do not seem to take effect straight away. That is, the changes do not appear immediately on screen.

Here is a simplified version of the code I'm running:

- (void) do_ui_update {
    // UI update here that does not appear immediately
}

- (void) some_time_consuming_function {
    // line 1
    // line 2
    // ...
    // line n
}

- (void) function_that_runs_in_main_thread {
    [self RUN_ON_UI_THREAD:^{
        [self do_ui_update];

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self some_time_consuming_function];
        });
    }];
}

- (void) RUN_ON_UI_THREAD:(dispatch_block_t)block 
{
    if ([NSThread isMainThread])
        block();
    else
        dispatch_sync(dispatch_get_main_queue(), block);
}

When I debug setting breakpoints at each line in some_time_consuming_function, sometimes the UI updates appear on screen when the debugger hits line 2, sometime line 3, and so on.

So my question is: How can I make the UI updates appear on screen before the very first line of some_time_consuming_function is reached?

Upvotes: 1

Views: 145

Answers (1)

Mats
Mats

Reputation: 8638

Dispatch the background dispatch to the next main loop iteration:

-(void) function_that_runs_in_main_thread {
    [self do_ui_update];

    dispatch_async(dispatch_get_main_queue(), ^{
        // All pending UI updates are now completed
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self some_time_consuming_function];
        });
    });
}

Upvotes: 1

Related Questions