在我的應用程序中,我允許用戶拍攝照片以與給定任務關聯。我的方法是使用此category創建具有自定義名稱的ALAssetsGroup並將照片保存到其中。當我去抓取所有這些照片並將它們顯示爲縮略圖時,問題就出現了。我抓住了資產這樣的:枚舉ALAssetsLibrary
- (void)setImagesForTask:(Task *)task {
//clear images associated with the task so we don't double up.
[task clearImages];
//static instance of ALAssetsLibrary
lib = [JobStore defaultAssetsLibrary];
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^(void){
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSLog(@"group:%@", group);
//find my custom photo album and if it's there, enumerate through it.
if (group != nil && [[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:
[NSString stringWithFormat:@"Media for %@", task.title]]) {
if (group.numberOfAssets != 0) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result != nil) {
CGImageRef imgRef = [[result defaultRepresentation] fullScreenImage];
UIImage *img = [UIImage imageWithCGImage:imgRef];
//methods to resize the image and get PNG representations…
[task setThumbnailDataFromImage:img];
[task setLargeImageDataFromImage:img];
NSLog(@"saved image to: %@", group);
} else if (result == nil){
NSLog(@"enumeration of assets ended");
}
}];
}
//if the group isn't there...
} else if (group == nil) {
//this method removes a UIView with a UIActivityIndicatorView that appears while enumeration occurs.
[self performSelectorOnMainThread:@selector(removeView)
withObject:nil
waitUntilDone:NO];
NSLog(@"enumeration of groups ended");
}}
failureBlock:^(NSError *error) {
NSLog(@"FAILURE");
}];
});
JobStore *js = [JobStore defaultStore];
[js saveChanges];
}
這是我得到的異常:
2012-04-02 10:05:26.585 MyApp[2746:7d3b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSOrderedSet enumerateObjectsAtIndexes:options:usingBlock:]: index 0 beyond bounds for empty ordered set'
異常拋出在enumerateAssetsUsingBlock:方法。如果我將照片添加到一個任務,導航到另一個任務並將照片添加到該任務,則這種情況特別容易發生。 一個奇怪的是,拋出異常之前,我有這個在我的日誌:
2012-04-02 10:05:26.580 MyApp[2746:707] group:ALAssetsGroup - Name:Media for (current task), Type:Album, Assets count:1
因此該資產組實際上不是空的,但是當我試圖在其中列舉的資產,我的應用程序似乎認爲那裏什麼都沒有。 在我看來,也許是因爲我有這些枚舉嵌套和/或因爲塊在後臺執行,但方法立即返回,我試圖枚舉資產組之前,我的應用程序知道它包含任何東西。有沒有最好的方法來解決這個問題?我認爲有一些基本知識我不瞭解這些方法的塊如何執行。任何投入將不勝感激。
感謝那些你認爲這一問題。我相信我已經解決了這個問題,而且這個問題在我看來是一個糟糕的設計決定。我今天會發佈一個答案,但還不能由於代表不夠。 – geraldWilliam 2012-04-02 18:35:13