2012-01-22 94 views
1

我想將塊內的結果分配給塊變量。這裏是我的代碼:__block變量不保留

__block UIImage *latestImage; 
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init]; 

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos. 
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos 
           usingBlock:^(ALAssetsGroup *group, BOOL *stop){ 
            // Within the group enumeration bl ock, filter to enumerate just photos. 
            [group setAssetsFilter:[ALAssetsFilter allPhotos]]; 

            // Chooses the photo at the last index 
            [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)] 
                  options:0 
                 usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop){ 
                  // the end of the enumeration is signaled by asset == nil. 
                  if (alAsset){ 
                   ALAssetRepresentation *representation = [alAsset defaultRepresentation]; 
                   latestImage = [UIImage imageWithCGImage:[representation fullResolutionImage]]; 
                  } 
                 }]; 
           } 
          failureBlock: ^(NSError *error){ 
           // handle error 
           NSLog(@"No groups"); 
          } 
]; 
return latestImage; 

我確認變量latestImage是通過在塊內部的UIImageView中顯示來設置的。但是,當我嘗試返回上述代碼中顯示的對象時,它不返回任何內容。

我錯過了什麼?

謝謝。

回答

0

enumerateGroupsWithTypes:usingBlock:failureBlock:是異步的。在塊有機會設置變量之前,您正在返回latestImage。從ALAssestsLibrary的文檔:

許多由ALAssetsLibrary聲明的方法以失敗塊 作爲參數。這些方法都是異步的,因爲可能需要用戶 授予對數據的訪問權限。

您可以將整個函數包裝在dispatch_sync()中或使用信號量等待答案。無論哪種方式,請確保您沒有在主線程中執行此操作。