如何在任务完成块中更新UI?

Ste*_*Hsu 4 cocoa cocoa-touch objective-c-blocks

在我的应用程序中,我在发送HTTP请求之前让进度指示器开始动画.完成处理程序在块中定义.收到响应数据后,我从块内隐藏进度指示器.我的问题是,正如我所知,UI更新必须在主线程中执行.我怎么能确定它?

如果我在窗口控制器中定义一个更新UI的方法,让块调用方法而不是直接更新UI,那么它是一个解决方案吗?

gcb*_*ann 10

此外,如果您的应用针对iOS> = 4,您可以使用Grand Central Dispatch:

dispatch_async(dispatch_get_main_queue(), ^{
    // This block will be executed asynchronously on the main thread.
});
Run Code Online (Sandbox Code Playgroud)

当使用performSelect…方法采用的单个选择器和对象参数无法轻松表示自定义逻辑时,这非常有用.

要同步执行块,请使用dispatch_sync() - 但请确保您当前没有在主队列上执行,否则GCD将会死锁.

__block NSInteger alertResult; // The __block modifier makes alertResult writable
                               // from a referencing block.
void (^ getResponse)() = ^{
    NSAlert *alert = …;
    alertResult = [NSAlert runModal];
};

if ([NSThread isMainThread]) {
    // We're currently executing on the main thread.
    // We can execute the block directly.
    getResponse();
} else {
    dispatch_sync(dispatch_get_main_queue(), getResponse);
}

// Check the user response.
if (alertResult == …) {
    …
}
Run Code Online (Sandbox Code Playgroud)