简体   繁体   中英

return object on Main thread GCD

I want to return an array of cached images. See the code. I simply want to return the array I've created, but I can't in the dispatch_get_main_queue and I don't know how to alter the code to return the array. I'm sure this is easy, but I struggle with the lower level C / GCD syntax. Thanks.

-(NSArray *)returnArray
{

    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"something" ofType:@"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];

    NSMutableArray *finalArray = [[NSMutableArray alloc] initWithCapacity:array.count];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);


    dispatch_async(queue, ^{
       ]
        for(int i=0;i<array.count; i++) {

            NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[array objectAtIndex:i]];

            UIImage *frameImage = [UIImage imageWithContentsOfFile: filePath];
            UIGraphicsBeginImageContext(frameImage.size);
            CGRect rect = CGRectMake(0, 0, frameImage.size.width, frameImage.size.height);
            [frameImage drawInRect:rect];
            UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            [finalArray addObject:renderedImage];

        }

        dispatch_sync(dispatch_get_main_queue(), ^{
            //THIS IS WHAT IM TRYING TO DO, BUT I CANT
            return finalArray;
        });

    });

}

You cannot do this without sacrificing asynchrony. You'll need to create a function that takes that value as an argument, and call it passing finalArray as the argument. So instead of your control flow looking like this (-> indicating "calls" and <- indicating "returns"):

returnArray -> 
    async (private queue) -> 
        sync (main queue) <-
    ... <-
returnArray <-

It will look like this:

returnArray -> 
    async (private queue) -> 
        sync (main queue) ->
            useArray (array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM