如何等待异步调度块完成?我正在测试一些使用Grand Central Dispatch进行异步处理的代码。测试代码如下所示:[object runSomeLongOperationAndDo:^{
STAssert…}];测试必须等待操作完成。我目前的解决方案如下:__block BOOL finished = NO;[object runSomeLongOperationAndDo:^{
STAssert…
finished = YES;}];while (!finished);看起来有点粗糙,你知道更好的方法吗?我可以通过调用暴露队列然后阻塞dispatch_sync:[object runSomeLongOperationAndDo:^{
STAssert…}];dispatch_sync(object.queue, ^{});......但是这可能会暴露太多object。
3 回答
梦里花落0921
TA贡献1772条经验 获得超5个赞
我最近再次讨论这个问题并写了以下类别NSObject
:
@implementation NSObject (Testing)- (void) performSelector: (SEL) selector withBlockingCallback: (dispatch_block_t) block{ dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [self performSelector:selector withObject:^{ if (block) block(); dispatch_semaphore_signal(semaphore); }]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); dispatch_release(semaphore);}@end
通过这种方式,我可以轻松地将异步调用与回调转换为测试中的同步调用:
[testedObject performSelector:@selector(longAsyncOpWithCallback:) withBlockingCallback:^{ STAssert…}];
- 3 回答
- 0 关注
- 747 浏览
添加回答
举报
0/150
提交
取消