2012-07-31 53 views
0

我試圖從ALAssetLibrary中獲取視頻,以便我可以用它做任何事情。我使用的塊來做到這一點:使異步塊在其他代碼之前運行

NSMutableArray *assets = [[NSMutableArray alloc] init]; 

library = [[ALAssetsLibrary alloc] init]; 

NSLog(@"library allocated"); 

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos. 

[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { 

    NSLog(@"Begin enmeration"); 

    [group setAssetsFilter:[ALAssetsFilter allVideos]]; 

    NSLog(@"Filter by videos"); 

    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1] 

          options:0 

         usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { 

          NSLog(@"Asset retrieved"); 

          if (alAsset) { 

           ALAssetRepresentation *representation = [alAsset defaultRepresentation]; 

           NSURL *url = [representation url]; 

           AVAsset *recentVideo = [AVURLAsset URLAssetWithURL:url options:nil]; 

           [assets addObject:recentVideo]; 

           NSLog(@"Asset added to array"); 

          } 
         }]; 
} 

AVMutableComposition *composition = [[AVMutableComposition alloc] init]; 

NSLog(@"creating source"); 
AVURLAsset* sourceAsset = [assets objectAtIndex:0]; 

當我運行的代碼塊得到跳過和程序崩潰時,我嘗試訪問該元素的數組中,因爲它不存在。我被告知,這是因爲這些塊是異步的,但我不知道如何讓它們在所有其他操作之前運行。 performSelectorOnMainThread聽起來像它可能會這樣做,但我無法找到任何解釋我將如何去做這件事。

回答

0

如果你想

AVMutableComposition *composition = [[AVMutableComposition alloc] init]; 

NSLog(@"creating source"); 
AVURLAsset* sourceAsset = [assets objectAtIndex:0]; 

group枚舉後發生的,然後把它的第一個塊內,但在枚舉後:

AVMutableComposition *composition = [[AVMutableComposition alloc] init]; 
__block AVURLAsset* sourceAsset = nil; 
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { 

    // snip... 

    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1] 
          options:0 
         usingBlock:^{ 
          // snip... 
         }]; 
    sourceAsset = [assets objectAtIndex:0]; 
    // Now do other things that depend on sourceAsset being set 
}]; 

__block關鍵字允許指針被設置爲塊內的新對象;否則變量不能重新分配。

+0

我確實需要它,但也有一堆其他代碼也必須在它之後運行。我想這可能是最好的嘗試,並將枚舉放入其自己的函數中,我也分配源資源,然後執行所有其他的任務,但是我擔心即使將它放入函數它仍然會很奇怪。不過,猜猜我永遠不會知道。 – lunadiviner 2012-08-01 21:07:06

相關問題