'NSRangeException',原因:'* - [__ NSArrayM objectAtIndex:]:索引2超出边界[0 .. 1]'

时间:2012-11-18 20:51:25

标签: iphone ios nsrangeexception

我试图删除一些项目但我收到此NSException:

' NSRangeException',原因:' * - [__ NSArrayM objectAtIndex:]:索引2超出界限[0 .. 1]'

这是我的代码:

-(void)deletePressed:(id)sender {

if (data.count > 0) {

    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/Galeria/"];

    NSFileManager *manager = [NSFileManager defaultManager];

    for (NSIndexPath *indexPath in itensSelecionados) {

        NSString *result = [path stringByAppendingFormat:@"%@", [[manager contentsOfDirectoryAtPath:path error:nil] objectAtIndex:indexPath.row]];

        [manager removeItemAtPath:result error:nil];

    }

    [self viewWillAppear:YES];

}}

任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:2)

您无法从正在迭代的数组中删除对象 您可能没有什么解决方案。

一个是使用一个额外的可变数组,它将保存所有应删除的对象,然后遍历它并从原始数组中删除对象:

-(void)deletePressed:(id)sender {
    if (data.count > 0) {
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/Galeria/"];
        NSFileManager *manager = [NSFileManager defaultManager];
        NSMutableArray *filesToDelete = [NSMutableArray array];

        // Build a list of files to delete
        for (NSIndexPath *indexPath in itensSelecionados) {
            NSString *result = [path stringByAppendingFormat:@"%@", [[manager contentsOfDirectoryAtPath:path error:nil] objectAtIndex:indexPath.row]];
            [filesToDelete addObject:result];
        }

        // Actually delete the files
        for (NSString *indexPathString in filesToDelete) {
            [manager removeItemAtPath:indexPathString error:nil];
        }

        // Why do you call viewWillAppear directly ??
        [self viewWillAppear:YES];
    }
}

修改
由于Thiago的建议,修正了第二次迭代中的NSIndexPathNSString

答案 1 :(得分:0)

您需要按反向行顺序删除。假设您有3行,并且要删除索引0和2处的行。

如果首先删除索引0处的行,那么当您尝试删除索引2处的行时,它会崩溃,因为现在只剩下2行了。

如果先删除索引2处的行,则索引0,一切都会正常。