【问题标题】:App crashes with 'NSRangeException' when library is empty当库为空时,应用程序因“NSRangeException”而崩溃
【发布时间】:2013-05-10 12:57:40
【问题描述】:

我正在使用此代码从 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];

感谢您的帮助!

【问题讨论】:

  • 就在崩溃的行之前。

标签: ios alassetslibrary alasset nsrange nsrangeexception


【解决方案1】:

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

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];

【讨论】:

  • 谢谢!正是我想要的,一切都很完美。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 2016-03-20
  • 2013-02-04
  • 2023-03-14
  • 2019-12-26
  • 2012-05-28
  • 1970-01-01
相关资源
最近更新 更多