objective c - Enforcing order with ALAssetsLibrary enumeration blocks -
i’m doing iterations using apple’s alassetslibrary framework. need iteration finish before start playing videos.
here reducted sample code shows problem i’m having.
@property (nonatomic) nsmutablearray *assetstoplay; - (void)viewdidload { alassetslibrary *library = [[alassetslibrary alloc] init]; [library enumerategroupswithtypes:alassetsgroupall usingblock:^(alassetsgroup *group, bool *stop) { [group enumerateassetsusingblock:^(alasset *result, nsuinteger index, bool *stop) { avasset *asset = <#get asset#> [self.assetstoplay addobject:asset]; }]; } failureblock:nil]; [self playem]; // bug: code invoked immediately. run after above block iteration finished. } - (void)playem { for(avasset *asset in self.assetstoplay) { nslog(@"%@", asset); } }
to elad's point, enumeration method runs asynchronously, , group
nil
when done.
so, asynchronous situations, should move call playem
inside completion block rather after it. want call playem
when group
nil
(i.e. you're done enumerating):
[library enumerategroupswithtypes:alassetsgroupall usingblock:^(alassetsgroup *group, bool *stop) { if (group) { // if `group` non-`nil`, still enumerating groups [group enumerateassetsusingblock:^(alasset *result, nsuinteger index, bool *stop) { if (result) { // note, if `result` not `nil` (`nil` signifies end of asset enumeration) avasset *asset = <#get asset#> [self.assetstoplay addobject:asset]; } }]; } else { // if `group` `nil`, done enumeration, call method [self playem]; // called when enumeration done. } } failureblock:^(nserror *error) { // handle user's rejection of permission here }];
Comments
Post a Comment