Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Method's return value and Completion block, how are they executed?

I make an photography app in iPhone and I have these 3 classes: ViewController, CaptureManager, and ImgProcessor.

ViewController:

-(IBAction)takePic:(id)sender{
     images = [captureManager takeMultipleImagesWithCompletion:^{

          //Some UI related code..

          [imgProcessor process:images];
     }];
}

CaptureManager:

-(NSArray *)takeMultipleImagesWithCompletion:^(void)completionHandler{

     // take picture codes...

     completionHandler();

     return arrayOfImagesTaken;
}

So far it works as desired: imgProcessor processes the images taken by captureManager. But I don't quite get the idea how this works. Bcos I called completionHandler before I return the array of images taken. How did this code executed? Is there a better solution to this?

Thanks!

like image 538
yonasstephen Avatar asked Jan 17 '26 23:01

yonasstephen


1 Answers

You don't need to return the value images. You can pass it as an argument for the cmpletionHandler block.

-(void)takeMultipleImagesWithCompletion:(void (^)(NSArray *images))completionHnadler{

     // take picture codes...
     completionHnadler(arrayOfImagesTaken);
}

You can call it like this :

-(IBAction)takePic:(id)sender{
      [captureManager takeMultipleImagesWithCompletion:^(NSArray *images){
           [imgProcessor process:images];
     }];
}

How it works ?

Here the block is used as a callback, it defines the code to be executed when a task completes. When the takeMultipleImagesWithCompletion is finished running, the block completionHnadler will be called.

like image 181
samir Avatar answered Jan 20 '26 12:01

samir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!