我有一个方法myButtonAction
它执行一些繁重的计算,我需要在后台线程上运行,同时我在主线程中加载一个指示“任务进度”的 View 。一旦后台线程完成执行该方法,我需要删除“任务进度” View 并在主线程中加载另一个 View 。
[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];
我面临的问题是,在
myButtonAction
之前完成执行,LoadView
完成其执行。我怎样才能确定 LoadView
仅在 myButtonAction
之后才开始执行完成其执行。注:
myButtonAction
在另一个类中有它的方法定义。
最佳答案
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];
}
关于iphone - 如何保证线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11220556/