2011-06-23 46 views
0

我需要用ALAssets中的UIImage實例填充許多UIImageView實例(約10個)。我不想鎖定主線程,所以想在後臺線程中儘可能多地執行。從ALAsset獲取CGImage是最耗時的,所以我想把它放在後臺線程中。從ALAssetRepresentation獲取fullScreenImage在後臺線程

我遇到的問題是隻有第一個圖像實際上被正確加載。任何其他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]; 
} 

我不知道爲什麼這不能正常工作。有任何想法嗎?

回答

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

乾杯,

亨德里克

+0

感謝,會給一個去! – adriaan