我正在尝试删除一些项目,但我收到此NSException:
'NSRangeException', reason: '* -[__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];
}}
有人可以帮忙吗?
不能从要迭代的数组中删除对象。
可能很少有适合您的解决方案。
一种是使用一个额外的可变数组,该数组将保存所有应该删除的对象,然后遍历它并从原始数组中删除对象:
-(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];
}
}
编辑
由于蒂亚戈的建议,修复了第二次迭代中NSIndexPath
NSString
。
您需要按相反的行顺序进行删除。假设您有 3 行,并且想要删除索引 0 和 2 处的行。
如果先删除索引 0 处的行,则当您尝试删除索引 2 处的行时,它会崩溃,因为现在只剩下 2 行了。
如果先删除索引 2 处的行,然后删除索引 0,则一切正常。