块的执行总是被延迟 [英] The execution of block is always delayed

查看:73
本文介绍了块的执行总是被延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对IOS很陌生.我想在viewDidLoad中的设备上获取所有图片.但是该块总是在我在代码中调用NSLog(@"%d", photos.count)之后执行,如下所示.如何处理这种情况?

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

推荐答案

作为

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:

此方法是异步的.枚举组时,可能会要求用户确认应用程序对数据的访问;但是,该方法会立即返回.您应该对 enumerationBlock 中的资产执行任何所需的工作.

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.

这篇关于块的执行总是被延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆