在线程 AI 中调用一个异步服务,该服务在线程 B 中运行。服务完成后调用一个委托方法。我希望线程 A 等到线程 B 完成。我为此使用了 NSCondition。
这是我的设置(跳过不重要的东西):
-(void)load
{
self.someCheckIsTrue = YES;
self.condition = [[NSCondition alloc] init];
[self.condition lock];
NSLog(@"log1");
Service *service = // set up service
[service request:url delegate:self didFinishSelector:@selector(response:)];
while (self.someCheckIsTrue)
[self.condition wait];
NSLog(@"log3");
[self.condition unlock];
}
-(void)response:(id)data
{
NSLog(@"log2");
[self.condition lock];
self.someCheckIsTrue = NO;
// do something with the response, doesn't matter here
[self.condition signal];
[self.condition unlock];
}
出于某种原因,只打印“log1”,“log2”和“log3”都没有。我认为这就是为什么委托方法响应由“服务线程”调用,即线程 B,而load由线程 A 调用。
我也尝试了信号量,但也不起作用。这是代码:
-(void)load
{
NSLog(@"log1");
Service *service = // set up service
self.sema = dispatch_semaphore_create(0);
[service request:url delegate:self didFinishSelector:@selector(response:)];
dispatch_semaphore_wait(self.sema, DISPATCH_TIME_FOREVER);
NSLog(@"log3");
}
-(void)response:(id)data
{
NSLog(@"log2");
// do something with the response, doesn't matter here
dispatch_semaphore_signal(self.sema);
}
我怎样才能让它工作?