How can I make a block execute synchronously, or make the function wait for the handler before the return statement, so the data can be passed back from the block?
-(id)performRequest:(id)args
{
__block NSData *data = nil;
[xyzclass requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
data = [NSData dataWithData:responseData];
}];
return data;
}
are you sure you want to do it synchronously ? if yes, you can call (or put) your handler function in your block or use Jignesh advice (and use “performSelectorInMainThread” when your handler is finished and you want to return values.
the asynchronous way is (a little bit) harder, but better as: - it forces you to write clean code (no passing of convenient variables) - you can execute other thing so the users won't wait and think your app is slow.
you should really give it two or three hours to go asynchronous. small pain for full gain. you can also have a look to Key-Value Observing.
async is almost always better. but if you want synchronous:
Disclaimer: CocoaCouchDeveloper says that of course this will only work if the completion block and the runloop are on the same thread. I assumed that because many(most) COMPLETION handler I know work that way but of it is valid in principle.
The above is not thread safe
use a semaphore or something maybe.
also I said I don't promote this
You could do like this.
You can do synchronous request in another thread like below code
From Main thread you can call this
or else you can do asynchronous request using following method
and implement delegate methods for NSURLConnection
You can use semaphores in this case.
semaphore will block execution of further statements until signal is received, this will make sure that your function does not return prematurely.
You could just add a method which processes the returned data and call that in your block: