Within a thread A I call an asynchronous service, which runs in thread B. The service calls a delegate method once finished. I want thread A to wait until thread B finishes. I used NSCondition for this.
This is my set up (skipped the unimportant stuff):
-(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];
}
For some reason, only "log1" is printed, neither "log2" nor "log3". I assume it's why the delegate method response is called by the "service thread", which is thread B, whereas load is called by thread A.
I also tried a Semaphore, but doesn't work either. Here is the code:
-(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);
}
How can I get this to work?