1

我有一个myButtonAction执行一些繁重计算的方法,我需要在后台线程上运行它,同时我正在加载一个在主线程中指示“任务进度”的视图。一旦后台线程完成执行该方法,我需要删除“任务进度”视图并在主线程中加载另一个视图。

[self performSelectorInBackground:@selector(myButtonAction) withObject:nil];
[self performSelectorOnMainThread:@selector(LoadView) withObject:nil waitUntilDone:YES];

我面临的问题是,在myButtonAction完成执行之前,LoadView完成了它的执行。如何确保仅在完成LoadView执行后才开始执行。myButtonAction

注意:myButtonAction在另一个类中有它的方法定义。

4

4 回答 4

2

使用Grand Central Dispatch

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];
}
于 2012-06-27T06:43:41.107 回答
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

于 2012-06-27T06:30:29.957 回答
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 更新完成。

于 2012-06-27T06:36:07.070 回答
0

为了这些目的,我使用了信号量设计模式

于 2012-06-27T06:45:28.263 回答