我有一个方法myButtonAction
执行一些繁重的计算,我需要在后台线程上运行,而我在主线程中加载一个指示“任务进度”的视图。一旦后台线程完成执行该方法,我需要删除“任务进度”视图并在主线程中加载另一个视图。
[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
我面临的问题是,在myButtonAction
完成执行之前,LoadView
完成了它的执行。如何LoadView
仅在myButtonAction
完成执行后才开始执行。
注意:myButtonAction
在另一个类中有其方法定义。
答案 0 :(得分:2)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self myButtonAction];
dispatch_async(dispatch_get_main_queue(), ^{
[self LoadView];
});
});
或者,如果您想继续使用performSelector
方法:
[self performSelectorInBackground:@selector(loadViewAfterMyButtonAction) withObject:nil];
,其中
- (void)loadViewAfterMyButtonAction
{
[self myButtonAction];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
}
答案 1 :(得分:1)
您需要执行以下操作 -
[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
- (void)myButtonAction {
//Perform all the background task
//Now switch to main thread with all the updated data
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
}
编辑 - 然后你可以尝试 -
[self performSelectorInBackground:@selector(buttonActionInBackground) withObject:nil];
- (void)buttonActionInBackground {
[self myButtonAction];
//Now switch to main thread with all the updated data
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
}
现在您无需更改myButtonAction
。
答案 2 :(得分:0)
我认为在myButtonAction结束时调用此代码:
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
现在难怪LoadView在myButtonAction完成之前完成,因为你说它要等到“waitUntilDone:YES”完成。最后用waitUntilDone调用它:NO。
对于这类问题的简单解决方案,请看一下使用[self performSelector:@selector(sel) withObject:obj afterDelay:0.0]
或NSTimer将选择器调用放入主运行循环 - 例如,如果您想等到UI更新完成。
答案 3 :(得分:0)
我出于这些目的使用Semaphore Design Pattern。