執行TableView的deleteRowsAtIndexPaths報Invalid update錯誤
在網上搜索了一大堆,發現都說得沒頭沒尾的。其實最主要的原因是在執行deleteRowsAtIndexPaths方法前要將列表資料來源中對應的位置的資料刪除掉,不然在執行這個方法後就會報錯。比如原來列表中有10條資料的,現在想刪除一條資料,可是在沒有將該條資料從資料來源中刪除或者沒有刪除成功時,就去執行deleteRowsAtIndexPaths方法,UITableViewController不會去檢查你是否刪除成功,它就認為現在是9條資料,但是當它檢查當前資料數量時發現現在數量還是10條,與要求不符合,所以就報如下錯誤:
2018-04-11 23:42:12.412066+0800MyNotesObjc[3050:108200] *** Assertion failure in -[UITableView_endCellAnimationsWithContext:],/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3698.33.6/UITableView.m:2011
2018-04-11 23:42:12.419054+0800MyNotesObjc[3050:108200] *** Terminating app due to uncaught exception'NSInternalInconsistencyException', reason: 'Invalid update: invalid number ofrows in section 0. The number of rows contained in an existing sectionafter the update (2) must be equal to the number of rows contained in thatsection before the update (2), plus or minus the number of rows inserted ordeleted from that section (0 inserted, 1 deleted) and plus or minus the numberof rows moved into or out of that section (0 moved in, 0 moved out).'
下面是我對這個問題做的一個記錄:
(1)錯誤資訊:
2018-04-11 23:42:12.412066+0800MyNotesObjc[3050:108200] *** Assertion failure in -[UITableView_endCellAnimationsWithContext:],/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3698.33.6/UITableView.m:2011
2018-04-11 23:42:12.419054+0800MyNotesObjc[3050:108200] *** Terminating app due to uncaught exception'NSInternalInconsistencyException', reason: 'Invalid update: invalid number ofrows in section 0. The number of rows contained in an existing sectionafter the update (2) must be equal to the number of rows contained in thatsection before the update (2), plus or minus the number of rows inserted ordeleted from that section (0 inserted, 1 deleted) and plus or minus the numberof rows moved into or out of that section (0 moved in, 0 moved out).'
(2)錯誤程式碼:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
Note *note = self.listData[indexPath.row];
//獲得DAO物件
NoteDAO *dao = [NoteDAOsharedInstance];
//刪除資料
[dao remove:note];
//重新查詢所有資料
self.listData = [dao findAll];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
(3)錯誤原因:
由於在執行刪除資料時,執行失敗了,沒有刪除成功。導致重新查詢所有資料後資料還是原來的數量,沒有減少。而程式在更新資料時,發現數據並沒有減少,與要求的數量不對,從而報錯。
(4)解決辦法:
檢查NoteDAO類中的的remove方法,發現是由於在對比時間時失敗了,導致沒有刪除成功,解決了這個問題後報錯也解決了。
// 刪除Note方法
- (int)remove:(Note *)model {
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:self.plistFilePath];
for (NSDictionary *dict in array) {
NSString *strDate = dict[@"date"];
NSDate *date = [self.dateFormater dateFromString:strDate];
//比較日期主鍵是否相等
if ([date isEqualToDate:model.date]) {
[array removeObject:dict];
[array writeToFile:self.plistFilePath atomically:TRUE];
break;
}
}
return 0;
}