简体   繁体   中英

Fastest way to count the ALAssetLibrary?

I'm looking for the fastest way to count the number of items in the ALAssetLibrary. I don't, at least at this point, care /what/ is in there, just about many things there are.

For music/music videos it's easy:

MPMediaQuery* query = [[MPMediaQuery alloc] init];
int numItems = [[query items] count];

For ALAssetLibrary, the best I've been able to come up with is something crazy like this (typed by hand here, so could have errors):

    ALAssetsLibrary* assetLibrary = [[ALAssetsLibrary alloc] init];
    ALAssetsGroupType groupType = ALAssetsGroupAll;
    int numAssets=0;

    [assetLibrary enumerateGroupsWithTypes:groupType 
                                usingBlock:^(ALAssetsGroup* group, BOOL* stop){
         if (group)
         {
             [group enumerateAssetsUsingBlock:^(ALAsset* asset, NSUInteger index, BOOL* innerstop)
              {
                  if (asset)
                  {
                       numAssets++;
                  }
              }];
         }
     }];

I could see that if I only had 10 pictures/videos, but even on mobile devices, it's easily possible to have thousands.

Further, because it's in blocks, I'll have to set up locks around this code to make it synchronous, further slowing things down.

There's /got/ to be a better way to do this sort of thing. Anyone?

-Ken

There is, indeed, a better way:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
int __block numAssets = 0;
[library enumerateGroupsWithTypes:ALAssetsGroupAll
    usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group)
            numAssets += group.numberOfAssets;
        else
            NSLog(@"Asset count is: %i", numAssets);
        }
        failureBlock:^(NSError *err) {
            NSLog(@"Failure");
        }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM