主线程GCD上的返回对象

时间:2013-02-05 20:48:12

标签: iphone nsarray grand-central-dispatch

我想返回一个缓存图像数组。看代码。我只是想返回我创建的数组,但我不能在dispatch_get_main_queue中,我不知道如何更改代码以返回数组。我确信这很容易,但我很难用较低级别的C / GCD语法。感谢。

-(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;
        });

    });

}

1 个答案:

答案 0 :(得分:1)

如果不牺牲异步,就不能这样做。您需要创建一个将该值作为参数的函数,并调用它将finalArray作为参数传递。因此,而不是您的控制流看起来像这样( - &gt;表示“调用”和&lt; - 表示“返回”):

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

看起来像这样:

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