我写了一个简单的测试用例,遵循 Apple 的 documentation而且我没有看到我期望的结果。
代码如下:
- (void)testExample2
{
NSLog(@"1");
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"3");
dispatch_semaphore_signal(semaphore);
});
NSLog(@"2");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"4");
dispatch_release(semaphore);
}
我希望读取:1、2、3、4,但我的控制台只显示 1、3。
我已经能够在 while 循环中使用 DISPATCH_TIME_NOW
和 NSLoop hack 来解决这个问题,但是上面的代码应该有点工作......对吧?
干杯...
更新
我刚刚意识到我应该使用一个单独的队列而不是 dispatch_main_queue()
最佳答案
在我的tearDown
中完成了以下操作。
while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
NSLog(@"...Tearing Down Tests..");
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
dispatch_release(semaphore);
并将信号量创建推送到 setUp
中。
关于ios - Grand Central Dispatch 和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10733978/