在UITableView上删除行时出错(仅在iOS7中)

时间:2013-10-02 13:57:46

标签: iphone uitableview ios7 cell

我的应用程序在iOS6中运行很酷,但是当我使用与我一起使用的相同代码更新iOS7时,当我尝试删除表中的行时出现此错误:

2013-10-02 17:44:11.344 Goal[1877:a0b] *** Assertion failure in -[UITableView
     _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2903.2/UITableView.m:1330
2013-10-02 17:44:11.384 Goal[1877:a0b] *** Terminating app due to uncaught exception     'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows 
in section    0.  The number of rows contained in an existing section after the
 update (1) must be equal to    the number of rows contained in that section 
before the update (1), plus or minus the number   of rows inserted or 
 deleted from that section (0 inserted, 1 deleted) and plus or 
  minus the      number of rows moved into or out of that section  
(0 moved in, 0 moved out).'

如果需要,可以使用一些方法

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        // deleting
        NSManagedObjectContext *moc = self.managedObjectContext;
        Goal *goalToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
        [moc deleteObject:goalToDelete];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }

}
另一个

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"GoalCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
cell.textLabel.backgroundColor = [UIColor clearColor];

Goal *goal = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = goal.title;

return cell;
}

并且我没有忘记检查我的小区标识符,

3 个答案:

答案 0 :(得分:2)

我猜您收到错误是因为您在deleteRowsAtIndexPaths之前拨打了commitEditingStyle两次:更新了您的MOC后再次使用NSFetchedResultsControllerDelegate方法。

但真正的问题是你根本不应该打电话给deleteRowsAtIndexPaths

当用户操作删除某行时,表格视图会通过commitEditingStyle委托方法通知。然后,您的工作是更新数据模型,使其与表视图已知的内容保持一致。您无需通知该表。

只有在以编程方式修改数据模型时,才需要通过调用insert / delete / move方法通知表视图。

答案 1 :(得分:1)

错误信息非常清楚:

  • 更新前的行数= 1
  • 已删除的行数= 1
  • 更新后的行数= 1(应该为0)

您的numberOfRowsAtIndexPath方法实现错误。它应该比删除前的行数少1。此方法的返回值应与您希望在UITableView上拥有的行数匹配。

此外,您的代码将在任何iOS版本上崩溃,而不仅仅是7。

答案 2 :(得分:1)

在调用[tableView deleteRowsAtIndexPaths:@ [indexPath] withRowAnimation:UITableViewRowAnimationFade]之前; 减少numberOfRowsInSection函数返回的“numberOfRows”。