我有一个称为getCount:
的异步方法,它转到网址,计算一些东西,并在计数完成时调用回调。Obj-C同步使用块回调的异步方法
我有另一种同步的方法,需要将这些结果放入消息中,并返回该消息。下面是两个在一起:
- (NSString *)describe {
__block bool gotCount = NO;
[self getCount:^(int count) {
NSLog(@"Got the count: %i", count);
_count = count; // _count is an ivar of the object with this method.
gotCount = YES;
}];
// Pause here until the count has been fetched.
while (!gotCount) {
[NSThread sleepForTimeInterval:0.05];
}
return [NSString stringWithFormat:@"The count is %i", _count];
}
当我尝试这是我的回调不会被调用。它从不打印
Got the count 0
或此方案中计数的任何其他值。
如果我注释掉while循环,那条消息就会被打印出来。所以我知道getCount:
方法的工作原理,我的循环等待它到达时出现问题。
我需要getCount:
保持异步(还有其他地方,它被用在哪里更重要),我需要describe
保持同步。我该如何处理?
_Why_您需要'describe'等待返回吗? – 2014-10-08 19:12:34
直到我们看到'getCount:'的来源并知道'describe'正在运行什么队列时,我们才能真正知道发生了什么。我的猜测是,getCount:正在调度回调以与描述相同的串行队列运行。 – 2014-10-08 19:15:18
这种积极等待的形式非常糟糕......如果睡眠和回调在同一队列中,它也不起作用 – 2014-10-08 19:18:10