如何更新任务完成块中的UI? [英] How to update UI in a task completion block?
问题描述
在我的应用程序中,我让一个进度指示器开始动画,然后我发送一个HTTP请求。
完成处理程序在块中定义。在得到响应数据后,我隐藏了块内部的进度指示器。我的问题是,我知道,UI更新必须在主线程中执行。
In my application, I let a progress indicator starts animation before I send a HTTP request. The completion handler is defined in a block. After I get the response data, I hide the progress indicator from inside the block. My question is, as I know, UI updates must be performed in the main thread. How can I make sure it?
如果我在窗口控制器中定义一个更新UI的方法,并让块调用方法而不是直接更新UI,解决方案?
If I define a method in the window controller which updates UI, and let the block calls the method instead of updating UI directly, is it a solution?
推荐答案
此外,如果您的应用程序目标iOS> = 4,您可以使用Grand Central Dispatch:
Also, if your app targets iOS >= 4 you can use Grand Central Dispatch:
dispatch_async(dispatch_get_main_queue(), ^{
// This block will be executed asynchronously on the main thread.
});
这是非常有用的,当你的自定义逻辑不能轻易地用单选择器和对象参数表示 executeSelect ...
方法。
This is useful when your custom logic cannot easily be expressed with the single selector and object arguments that the performSelect…
methods take.
要同步执行一个块,使用 dispatch_sync code> - 但确保你当前没有在主队列上执行或GCD会死锁。
To execute a block synchronously, use dispatch_sync()
– but make sure you’re not currently executing on the main queue or GCD will deadlock.
__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 == …) {
…
}
这篇关于如何更新任务完成块中的UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!