2012-05-13 36 views
0

我試圖從保存的相冊中創建一個匹配特定條件的所有圖像的數組。這是一個簡化的代碼。我將這些照片添加到myImages數組中,並通過「已添加圖像」日誌進行確認,以便記錄正確的圖像。但是函數返回的數組總是空的。相當新的Objective-C,所以任何建議都會有幫助。數組保存的照片總是返回爲空

NSMutableArray * myImages = [NSMutableArray array]; 

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; 

// Enumerate just the photos by using ALAssetsGroupSavedPhotos. 
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { 

    // Within the group enumeration block, filter to enumerate just photos. 
    [group setAssetsFilter:[ALAssetsFilter allPhotos]]; 

    [group enumerateAssetsUsingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { 

          // The end of the enumeration is signaled by asset == nil. 
          if (alAsset) { 
           ALAssetRepresentation *representation = [alAsset defaultRepresentation]; 
           UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]]; 

            NSLog(@"Added Image"); 
            [myImages addObject:latestPhoto]; 
          } 
         }]; 
        } 
        failureBlock: ^(NSError *error) { 
         // Typically you should handle an error more gracefully than this. 
         NSLog(@"No groups"); 
        }]; 

return myImages; 

回答

0

什麼是imageTakenOnDate?那應該是myImages?如果是這樣,你不能以這種方式返回它,因爲該方法返回之後,塊代碼將執行。該方法是異步的。選項1:讓你的方法以一個完成塊作爲參數,然後調用enumerateGroupsWithTypes塊內的完成塊,然後再調用完成塊,並傳遞完成塊數組。例如:

typedef void (^CompletionBlock)(id, NSError*); 
-(void)myMethodWithCompletionBlock:(CompletionBlock)completionBlock; 

然後當你與成功調用來完成:

completionBlock(myImages, nil); 

,並在failureBlock電話:

completionBlock(nil, error); 

選項2:使數組的伊娃是保留在父對象上,而不是局部變量,然後將其聲明爲__block變量,以便可以在塊內修改它。

+0

是的,imagesTakenOnDate應該是myImages。我會閱讀你的建議並嘗試。謝謝! – vishwa

0

第一件事。你真的返回imagesTakenOnDate?在代碼中看不到任何對此ivar的引用。我會說你在你的代碼中加入了一些斷點。在gdb調試器控制檯中你可以輸入:

po myImages 

比調試器會打印出你的數組的內容。希望有幫助