0

起初我的表格视图是空的,然后您可以向其中添加自己的单元格。当您删除这些单元格时,一切正常。但是,如果您删除最后一个单元格,则我的 NSMutableArray 中没有对象,并且我在控制台中收到此错误(另外,我正在使用 Core Data 保存单元格):

 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[_PFBatchFaultingArray objectAtIndex:]: index (123150308) beyond bounds (1)'

我也尝试输入这行代码,但我仍然得到相同的结果:

//arr is my mutable array
        if ([arr count] == 0) {
        NSLog(@"No Cells");
    }

这就是我从表视图中删除对象的方式:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [arr removeObjectAtIndex:0];
        [context deleteObject:[arr objectAtIndex:0]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

我将如何解决这个问题?

4

2 回答 2

3

好的。

我在您的代码中发现了两个问题。

1-为什么要删除索引 0 处的每个时间对象?

2-从数组中删除对象而[arr removeObjectAtIndex:0];不是从同一索引数组中删除对象后,您将对象传递给核心数据以删除它

[context deleteObject:[arr objectAtIndex:0]];

这可能是问题所在。

这肯定会帮助你。

用这个:

[context deleteObject:[arr objectAtIndex:indexPath.row]];

[arr removeObjectAtIndex:indexPath.row];

谢谢 :)

于 2012-07-21T15:28:59.637 回答
0

如果您查看错误消息,您的代码失败的原因是因为您的某些代码正在寻找一个不存在的索引 123150308。如果没有看到您的完整代码,就不可能知道究竟是什么错误,但有一个简单的修复方法。

在异常是“预期行为”的代码中解决异常问题的一个好方法是使用@try块。这是您tableView使用@try块的方法:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        @try {
            [arr removeObjectAtIndex:0];
            [context deleteObject:[arr objectAtIndex:0]];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        @catch (NSRangeException *exception) {
            // Something was out of range; put your code to handle this case here
        }
    }
}

但是,如果没有应用程序其余部分的上下文,则无法判断这是否是错误。如果您尝试此操作但它不起作用,则错误在您的应用程序中更深

于 2012-07-21T15:30:25.643 回答