I\'m in the design stage for an app which will utilize a REST web service and sort of have a dilemma in as far as using asynchronous vs synchronous vs threading. Here\'s the sce
Just a thought: If you want to use the Unit Testing framework for the iPhone, you may want to have synchronous functionality, as that could make writing the tests easier.
However, some of your APIs may not work synchronously, so you need to turn them into sync tasks. Provided the code that performs the unit testing runs in its own thread, you can write a wrapper that will wait until the async task has finished.
To accomplish that, you'd use a semaphore: Your wrapper function starts the async operation and then uses the semaphore to block itself (i.e. puts itself to sleep). The callback that signals the end of the async event releases the semaphore, so that the sleeping wrapper thread can continue and return.
I would use dispatch_async with synchronous. This way, you have the advantage of no delegates/NSNotifications and it is non-blocking
- (NSArray *)users {
if(users == nil) {
users = do_sync_request();
}
return users;
}
// now when calling the users method, do this
- (NSArray *)getUsers {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *users = [self users];
dispatch_sync(dispatch_get_main_queue(), ^{
return users;
}
}
}