当库为空时,应用程序与“NSRangeException”崩溃

时间:2013-05-10 12:57:40

标签: ios alassetslibrary alasset nsrange nsrangeexception

我正在使用此代码从cameraRoll获取最新照片:

- (void) getTheLatestPhoto{
        ALAssetsLibrary *cameraRoll = [[ALAssetsLibrary alloc] init];
        [cameraRoll enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *images, BOOL *stop) {
            [images setAssetsFilter:[ALAssetsFilter allPhotos]];
            [images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
             {
                 if (result) {

                     ALAssetRepresentation *rep = [result defaultRepresentation];
                     self.sharingImage = [UIImage imageWithCGImage:[rep fullScreenImage]];
                 }
             }];
        }
                                failureBlock: ^(NSError *error) {
                                    NSLog(@"An error occured: %@",error);
                                }];
    }

实际上,如果库cameraRoll为空,则应用程序将因此错误而崩溃:

Terminating app due to uncaught exception 'NSRangeException', reason: 'indexSet count or lastIndex must not exceed -numberOfAssets'

据我所知,我的indexSet高于numberOfAssets:

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

此时我的问题是“我在哪里提出一个允许我检查资产是否为零的条件?”

如果cameraRoll大于零,我会让代码继续,但如果计数为零,我想以这种方式处理这个问题,反对让它崩溃:

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

if([images numberOfAssets]>0)行之前添加enumerateAssetsAtIndexes并继续代码...

if([images numberOfAssets]<=0)然后

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];