Grand Central Dispatch - display the first image when it is uploaded?

I just want to use other images for quick access. I use grand central dispatch to execute various blocks.

After starting the queue, I want to set the first image when it is done. With the current code below, unfortunately, the first image will only be displayed when all images are displayed.

So how can I change the code? Can I get a delegate when all the images are finished?

Here is the code:

// Async prerendering
    for (int i = 0; i < count; i++) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                UIImage* finalImage = [self prerenderImageForIndex:i];
                [self.imageArray addObject:finalImage];   

                // TODO: i want to display the first image. 
                // rendering goes on in the background 

               if (i==0 && [self.imageArray objectAtIndex:0] != nil ) {
                    self.image = [self.imageArray objectAtIndex:0];
                }
            });
        });
    }

Update:

-(UIImage*) prerenderImageForIndex:(int)frame {
 UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.frame.size.width, self.frame.size.height), NO, 0);      

        for (int i=0; i< [configurationArray count]; i++) {     
         //... get the layerName

        UIImage* layerImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:layerName ofType:@"png"]];

              // draw layer with blendmode and alpha 
        [layerImage drawInRect:CGRectMake(x, y, layerImage.size.width, layerImage.size.height) 
                     blendMode:layerblendmode 
                         alpha: layeralpha];

           }   

    // Get current context as an UIImage
    UIImage* finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

return finalImage;

}

I just want to know how can I cancel / stop or restart a running queue? Is it possible? Thank you for your help.

+5
source share
2 answers

, FIFO, :

dispatch_queue_t queue;
queue = dispatch_queue_create("myImageQueue", NULL);
for(int i = 0; i<count; i++) {
    dispatch_async(queue, ^{
        // do your stuff in the right order
    });
}

: http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

+2

, dispatch_async, , , , . , - , . , UI, .

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

    UIImage* finalImage = [self prerenderImageForIndex:i];
    [self.imageArray addObject:finalImage];

    if (i==0 && [self.imageArray objectAtIndex:0] != nil ) {
        dispatch_async(dispatch_get_main_queue(), ^{   
            self.image = [self.imageArray objectAtIndex:0];
        });
    }
});
+2

All Articles