Pergunta

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];
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top