从Detailview中删除Tableview的行

我已经在我的应用程序在我的详细视图中的故事板UITableView我通过tableview详细视图能够删除此行取决于某些行动,但给我下面的错误

 *** 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 (4) must be equal to the number of rows contained in that section before the update (4), 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).' 

如果删除表格中的最后一行,那么UITableView代码预计将剩余0行。 它调用你的UITableViewDataSource方法来确定剩下多less。 由于您有一个“无数据”单元,它返回1,而不是0.因此,当您删除表中的最后一行时,尝试调用-insertRowsAtIndexPaths:withRowAnimation:插入您的“无数据”行。

你需要做的是:

 // tell the table view you're going to make an update [tableView beginUpdates]; // update the data object that is supplying data for this table // ( the object used by tableView:numberOfRowsInSection: ) [dataArray removeObjectAtIndex:indexPath.row]; // tell the table view to delete the row [tableView deleteRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationRight]; // tell the table view that you're done [tableView endUpdates]; 

(根据这个链接 ,你应该避免NSInternalInconsistencyException 。)

添加或删除行时,必须更新数据源以保持一致性。 看来你的数据源在删除行后没有更新。 为了帮助你,你将使用你的数据源方法和你用来删除行的代码。

你的日志意味着4-1 = 3,而不是4

返回计数时必须考虑删除的行

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; 

你应该有一个variables或数组包含你的行数,例如

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.cellsCount; } // somewhere else [tableView beginUpdates]; self.cellsCount--; // here is an important line of code [tableView deleteRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationAutomatic]; [tableView endUpdates];