2013-02-26 24 views
3

我真的迷路了。 爲什麼我每次得到NSLog兩次UIImageassetsLibrary一個簡單的錯誤?

//------ get the images from the camera roll ---------- 
    assets=[[NSMutableArray alloc]init]; 
    NSMutableArray *cameraRollPictures=[[NSMutableArray alloc]init]; 
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init]; 
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) 
    { 

     NSInteger numberOfAssets = [group numberOfAssets]; 
     NSLog(@"NUM OF IMAGES:%d",numberOfAssets); 
     if (numberOfAssets > 0) 
     { 


      for (int i = 0; i <= numberOfAssets-1; i++) 
      { 

       [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) 
       { 
        UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]]; 
        [assets addObject:thumbnail]; 
        NSLog(@"theObject!!!! -- (%d) %@",i,thumbnail); 

      //******* for each i its here twice !! ******** 

       }]; 
      } 
     } 
+0

這似乎並不罕見,因爲您可能多次爲每個i進行枚舉。換句話說,如果你的'enumerateAssetsAtIndexes'方法爲每個i調用兩次(在你的外層循環中),那麼當然你會爲每個i得到多個NSLog()。 – Jeremy 2013-02-26 19:08:25

+0

@Jeremy:這就是我首先想到的,但是內部的'enumerateAssetsAtIndexes'被調用的索引集只包含單個索引'i',因此每個資產只枚舉一次。 – 2013-02-26 19:13:23

+0

我想我會同意如果我保證每個索引只調用一次usingBlock。 Apple文檔提到(關於usingBlock:_要使用indexSet中的索引來使用組中的每個資源的塊。這可以採用幾種方法,但從邏輯上看,它似乎會觸發每個資產都會導致他/她所描述的行爲。 – Jeremy 2013-02-26 19:23:54

回答

6

出於某種原因,enumerateAssetsAtIndexes(和enumerateAssetsUsingBlock)執行塊與result == nilindex == NSNotFound一個額外的調用在枚舉的末尾。

for (int i = 0; i <= numberOfAssets-1; i++) { 
    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) 
     { 
      if (result != nil) { 
       UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]]; 
       [assets addObject:thumbnail]; 
      } 
     }]; 
} 
:如果更改的NSLog()到

然後你會得到輸出

NUM OF IMAGES:2 
i=0, index=0, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=... 
i=0, index=2147483647, result=(null) 
i=1, index=1, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=... 
i=1, index=2147483647, result=(null) 

因此你必須檢查的result價值,而忽略一個nil值。這是顯而易見的

請注意,您可以將枚舉簡化爲

[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { 
    if (result != nil) { 
     UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]]; 
     [assets addObject:thumbnail]; 
    } 
}];