iOS UIView不会立即更新

时间:2016-07-13 14:37:14

标签: ios objective-c uiview

当我从主线程进行UI更新时,它们似乎不会立即生效。也就是说,更改不会立即显示在屏幕上。

以下是我正在运行的代码的简化版本:

- (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);
}

当我在some_time_consuming_function中的每一行调试设置断点时,有时当调试器遇到第2行,某些时候第3行时,UI更新会出现在屏幕上,依此类推。

所以我的问题是: 如何在到达some_time_consuming_function的第一行之前在屏幕上显示UI更新?

1 个答案:

答案 0 :(得分:1)

将后台调度分派给下一个主循环迭代:

-(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];
        });
    });
}