Iphone ';nsrange异常';,原因:';*-[u NSArrayM objectAtIndex:]:索引2超出界限[0..1]';

Iphone ';nsrange异常';,原因:';*-[u NSArrayM objectAtIndex:]:索引2超出界限[0..1]';,iphone,ios,nsrangeexception,Iphone,Ios,Nsrangeexception,我试图删除一些项目,但收到以下NSException: “NSRangeException”,原因:“*-[\uu NSArrayM objectAtIndex:]:索引2超出范围[0..1]” 这是我的密码: -(void)deletePressed:(id)sender { if (data.count > 0) { NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/Galeri

我试图删除一些项目,但收到以下NSException:

“NSRangeException”,原因:“*-[\uu 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];

}}

有人可以帮忙吗?

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

如果先删除索引0处的行,然后尝试删除索引2处的行时,它会崩溃,因为现在只剩下2行


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

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

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

-(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的建议,在第二次迭代中修复了
nsindepath
NSString

谢谢,它可以工作,但我需要在代码中做一些修改。第二个原因是:for(文件中的NSString*stringToDelete){[manager removeItemAtPath:stringToDelete error:nil];}我调用ViewWillDisplay,因为我需要在每次选择选项卡时重新加载表我仍然认为不应该直接调用
视图WillDisplay
。您最好将所有代码从该方法移动到另一个方法,并从两个位置调用它…谢谢,这是一个好主意,我将创建另一个方法来重新加载表,而不显示调用视图