您的代码中的问题是,无论您是否使用dispatch_sync
or dispatch_async
,STFail()
都将始终被调用,从而导致您的测试失败。
更重要的是,正如 BJ Homer 所解释的,如果您需要在主队列中同步运行某些东西,您必须确保您不在主队列中,否则会发生死锁。如果您在主队列中,您可以简单地将块作为常规功能运行。
希望这可以帮助:
- (void)testSample {
__block BOOL didRunBlock = NO;
void (^yourBlock)(void) = ^(void) {
NSLog(@"on main queue!");
// Probably you want to do more checks here...
didRunBlock = YES;
};
// 2012/12/05 Note: dispatch_get_current_queue() function has been
// deprecated starting in iOS6 and OSX10.8. Docs clearly state they
// should be used only for debugging/testing. Luckily this is our case :)
dispatch_queue_t currentQueue = dispatch_get_current_queue();
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if (currentQueue == mainQueue) {
blockInTheMainThread();
} else {
dispatch_sync(mainQueue, yourBlock);
}
STAssertEquals(YES, didRunBlock, @"FAIL!");
}