当后台任务完成后,如何在iPhone应用程序IOS程序中获取主UI线程的指示?
背景
答案 0 :(得分:3)
您可以使用-performSelectorOnMainThread:withObject:waithUntilDone:
从后台选择器回调主线程,如下所示:
- (void)loadModel
{
// Load the model in the background
Model *aModel = /* load from some source */;
[self setModel:aModel];
[self performSelectorOnMainThread:@selector(finishedLoadingModel) withObject:nil waitUntilDone:YES];
}
- (void)finishedLoadingModel
{
// Notify your view controller that the model has been loaded
[[self controller] modelLoaded:[self model]];
}
更新:更安全的方法是检查-finishedLoadingModel
以确保您在主线程上运行:
- (void)finishedLoadingModel
{
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:YES];
}
// Notify your view controller that the model has been loaded
[[self controller] modelLoaded:[self model]];
}
答案 1 :(得分:1)
在后台加载完成后,请从后台线程中调用以下内容:
[self performSelectorOnMainThread:@selector(backgroundLoadingDidFinish:) withObject:nil waitUntilDone:NO];
然后在RootViewController中实现-(void)backgroundLoadingDidFinish:(id)sender
。如果需要,您可以使用上述方法(withObject:
部分)传回数据。