Search code examples
objective-cxcodeioblockgrand-central-dispatch

In-line block definition - how to?


Right now I am dispatching a block of code inside a method to go download stuff for me using following format:

dispatch_queue_t downloader("downloader", NULL);
dispatch_async (downloader, ^{

//do stuff

});

what I am trying to do now is have that block return a UIImage for me, which I can then use as the return for the method:

-(UIImage *) myMethod:

dispatch_queue_t downloader("downloader", NULL);
dispatch_async (downloader, ^{

//do stuff to get UIImage

     dispatch_async (dispatch_get_main_queue, ^{

     return UIImage;  //this is the image that image I want myMethod to return

     });    
});

how ever I am getting passing parameter to incompatible type errors. I realize that is because I am not declaring that the block has a return value.

How can I declare that the block returns a UIImage right inside dispatch_async? Is this even possible or is would the method already be done by the time the block finishes execution?


Solution

  • Well, using the return would require your method to be synchronous, so there's no solution that way. You will need to use a block as part of the function, like this:

    - (void)myMethodOnFinish:(void(^)(UIImage *))finishBlock {
    
        dispatch_queue_t downloader("downloader", NULL);
        dispatch_async (downloader, ^{
    
            //do stuff to get UIImage
            UIImage *result = ...;
    
             dispatch_async (dispatch_get_main_queue, ^{
             //this is the image that image I want myMethod to return
                 finishBlock(result);
            });    
        });
    }
    

    and call like this:

    [self myMethodOnFinish:^(UIImage *image) {
    
        self.imageView.image = image; // or whatever you need to do            
    
    }];