0

我需要用来自 ALAssets 的 UIImage 实例填充一些 UIImageView 实例(大约 10 个)。我不想在这样做的时候锁定主线程,所以希望尽可能多地在后台线程中做。从 ALAsset 获取 CGImage 是最耗时的,所以我想把它放在后台线程中。

我遇到的问题是只有第一个图像实际上被正确加载。任何其他 UIImageView 实例最终都是空的。

下面是我的(简化的)代码。processAssets 方法遍历一个资产数组,并在后台线程上调用 loadCGImage。此方法从 ALAsset 获取 fullScreenImage 并将其传递给主线程上的 populateImageView,主线程使用它来生成 UIImage 并填充 UIImageView。

- (void)processAssets {   
    for(int i = 0; i < [assetArr count]; i++){
        ALAsset *asset = [assetArr objectAtIndex:i];
        [self performSelectorInBackground:@selector(loadCGImage:) withObject:asset];
    }
}

- (void)loadCGImage:(ALAsset *)asset
{    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    CGImageRef imgRef = CGImageRetain([[asset defaultRepresentation] fullScreenImage]);
    [self performSelectorOnMainThread:@selector(populateImageView:) withObject:imgRef waitUntilDone:YES];   
    CGImageRelease(imgRef);

    [pool release];
}

- (void)populateImageView:(CGImageRef)imgRef
{
    UIImage *img = [[UIImage imageWithCGImage:imgRef] retain];
    UIImageView *view = [[UIImageView alloc] initWithImage:image];
}

我不确定为什么这不能正常工作。有任何想法吗?

4

1 回答 1

3

你应该尝试这样的事情(使用块)

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    //load the fullscreenImage async
    dispatch_async(dispatch_get_main_queue(), ^{
      //assign the loaded image to the view.
    });
});

干杯,

亨德里克

于 2011-07-05T06:42:50.663 回答