2012-06-27 44 views
1

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

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

我现在面临的问题是,myButtonAction完成执行前,LoadView完成其执行。我如何确保LoadView只有在myButtonAction完成执行后才开始执行。

注:myButtonAction在另一个类中有其方法定义。

回答

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]; 
} 
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

+0

myButtonAction'在另一个类中,我不应该编辑它。 –

+0

@XaviValero - 查看编辑过的帖子,如果你想要,也可以去GCD。 – rishi

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更新完成。

0

我使用Semaphore Design Pattern这些目的。

+0

这就是我所说的完全过火。如第一个答案中所建议的GCD非常容易地解决了这个问题,对于程序员来说基本上没有任何努力,并且很少有错误的机会。 – gnasher729