The execution of block is always delayed

做~自己de王妃 提交于 2019-12-06 11:31:51

问题


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];

回答1:


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.



来源:https://stackoverflow.com/questions/9478456/the-execution-of-block-is-always-delayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!