Wait for synchronous tasks:
I'd recommend creating a new NSOperationQueue
, configure it to have as many threads as you need and then you launch your operations on that thread. To wait for them to complete, simply call waitUntilAllOperationsAreFinished
method.
For example:
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
// Add your tasks here
[operationQueue addOperationWithBlock:^{
// Long running task
}];
[operationQueue waitUntilAllOperationsAreFinished];
Be careful to not block the main thread or your Application will become unresponsive while it loads.
If you need something more complex than this, you can use the lower level API dispatch_group_t
to group threads and wait for them. Take a look at this response for a deeper explanation.
Wait for already asynchronous tasks:
Sometimes the methods described above are not enough, probably because you need to wait for an already asynchronous task (like enabling GPS or waiting for some external event). In these cases you can use a semaphore. You have to be very careful with error handling and semaphores, or you could block a thread forever.
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[object performLongOperationAndDo:^{
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
More info about Obj-C semaphores.
Unless necessary, I'd stick to NSOperationQueue
.