2012-01-22 90 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()中或使用信号量等待答案。无论哪种方式,请确保您没有在主线程中执行此操作。