Search code examples
iosccocoablock

Can a function return a value from an asynchronous block


Suppose this code without a block

int calculateValue (int a, int b) {
  return doSomeStuff(a,b);
}

now suppose the function depends on something that is asynchronous. So I declare the asynchronous part as a block like this

int calculateValue (int a, int b) {

   int (^myBlock)(int a, int b) = ^int(int a, int b) {
      // do some complex asynchronous stuff
      return result;
   };

// can I do this?
return myBlock;

}

Is there any need to put the calculation inside the block into a dispatch_sync on main thread or something?


Solution

  • No you can't do that. The point of starting an async function is so that the caller can continue on with other work (perhaps launch other async functions?).

    Assuming you are using dispatch_async() - from the docs:

    The dispatch_async() function returns immediately, without waiting for the block to be invoked:

    If you want to be able to work with result of the block from the caller you can pass in a reference to the caller as an argument to your block. Then when your async task is complete, call one of the caller's methods to pass your "return value".