2

I'm pretty new to IOS. I want to get all pictures on a device in viewDidLoad. but the block is always executed after I called NSLog(@"%d", photos.count) in the code as follows. How to handle such a case?

__block NSMutableArray* photos = [[[NSMutableArray alloc] init] retain];

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

void (^assertsEnumerator)(ALAsset *, NSUInteger , BOOL *) =  ^(ALAsset *result, NSUInteger index, BOOL *stop)
{
        if(result)
        {   
            NSLog(@"Assert name : %@", [result valueForProperty:ALAssetPropertyURLs]);         
            [photos addObject:[UIImage imageWithCGImage:[result aspectRatioThumbnail]]];   
        }
};

void (^groupEnumerator)(ALAssetsGroup*, BOOL*) = ^(ALAssetsGroup *group, BOOL *stop) {
    if(group != nil) {
        NSLog(@"Adding group %@", [group valueForProperty:ALAssetsGroupPropertyName]);
        [group enumerateAssetsUsingBlock: assertsEnumerator];
    }
};

[library enumerateGroupsWithTypes: ALAssetsGroupSavedPhotos
                       usingBlock:groupEnumerator
                     failureBlock:^(NSError * err) {NSLog(@"Erorr: %@", [err localizedDescription]);}];
[library release];
NSLog(@"%d", photos.count);
[photos release];
ayoy
  • 3,835
  • 19
  • 20
Jin
  • 23
  • 3

1 Answers1

3

As the ALAssetsLibrary documentation states, enumerateGroupsWithTypes:usingBlock:failureBlock: is asynchronous, so instead of being called in place, it's scheduled to be called from within the next run loop cycle. The documentation states clearly what's the reason for that and how you should proceed:

This method is asynchronous. When groups are enumerated, the user may be asked to confirm the application's access to the data; the method, though, returns immediately. You should perform whatever work you want with the assets in enumerationBlock.

ayoy
  • 3,835
  • 19
  • 20
  • Thanks, ayoy!What should I do if I need to return a value in enumerationBlock? And what should I do if I need that value in the coming callback function of delegate? – Jin Feb 28 '12 at 08:43
  • 1
    You simply can't do it, and you have to work around it somehow. See e.g. [this question and top answer](http://stackoverflow.com/questions/9474018/returning-uiimage-from-block) for more info. – ayoy Feb 28 '12 at 08:49