如何等待NSOperationQueue在单元测试中完成? [英] How do I wait until an NSOperationQueue has finished in a Unit Test?
问题描述
问题
- 我有一个NSOperationQueue
logEntryGeneratorQueue
- 我要等待队列上的所有操作完成
我使用:
[logEntryGeneratorQueue waitUntilAllOperationsAreFinished];
如果添加到队列的线程在后台本身,它工作正常。
it works fine if the thread adding to the queue is in the background itself.
但是,如果我通过单元测试运行这个代码,它将在主线程上运行。所以我
想出了这个解决方案,我真的不喜欢:
However, if I'm running this code via a unit test, it'll be running on the main thread. So I came up with this "solution", which I really don't like:
if ([NSThread isMainThread]) {
while ([[logEntryGeneratorQueue operations] count] > 0) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
} else {
[logEntryGeneratorQueue waitUntilAllOperationsAreFinished];
}
这总是不太理想,但总是在10.5上正常工作。但是,现在我已经将我的项目升级到使用10.6 SDK,这打破了。
This was always less than ideal, but has always worked fine on 10.5. However, now I've upgraded my project to using the 10.6 SDK, and this breaks.
在一个测试中,它实际上在完成之前退出测试。我不知道为什么 - 我认为这是与NSOperationQueues工作方式不同的方式在10.6 - 他们现在使用GCD。
On one test, it actually quit the test before it completed. I've no idea why - I assume it's something to do with the way NSOperationQueues work differently in 10.6 - they now use GCD.
我试过的
What I've Tried
我试过用sleep替换runUntilDate,正如我想的,这意味着每个测试都会在这里暂停。
I've tried replacing the runUntilDate with sleep, which, as I thought, means every test pauses forever when it gets here.
我的问题
是否有更好的方法等待NSOperationQueue在主线程上完成?
Is there a better way to wait for an NSOperationQueue to finish on a main thread? If not, how can I get this code working under 10.6?
推荐答案
解决方案
我意识到我的代码是在一个永恒的循环,因为我在主线程调用 mergeChangesFromContextDidSaveNotification
,同时也等待队列完成主线程。因为合并更改在 waitUntilAllOperationsAreFinished
后调用,所以它从未被执行。
I realised that my code was in an eternal loop because I was calling mergeChangesFromContextDidSaveNotification
on the main thread whilst also waiting for the queue to finish on the main thread. And since the merge changes was called after waitUntilAllOperationsAreFinished
, it never got executed.
我认为答案是更改我从哪里运行NSOperationQueues。我不应该运行一个NSOperationQueue处理核心数据东西在主线程。我不应该真的在主线程上运行这个密集的东西,因为性能的原因,无论如何,我猜。
I think the answer is to change where I run NSOperationQueues from. I shouldn't run an NSOperationQueue that deals with core data stuff on the main thread. And I shouldn't really be running this intensive stuff on the main thread for performance reasons anyway I guess.
这篇关于如何等待NSOperationQueue在单元测试中完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!