刪除的效果
簡單刪除
先刪除數據源裡的數據,然後再刪除cell,否者會報錯
let indexPath = NSIndexPath.init(forRow: 1, inSection: 0)
let indexPath1 = NSIndexPath.init(forRow: 3, inSection: 0)
//title是數據源
self.titles.removeAtIndex(0)
self.titles.removeAtIndex(0)
self.tableView?.deleteRowsAtIndexPaths([indexPath,indexPath1], withRowAnimation: .Left)
```
如果先刪除cell,再刪除數據庫,會拋出exception
self.tableView?.deleteRowsAtIndexPaths([indexPath,indexPath1], withRowAnimation: .Left)
//title是數據源
self.titles.removeAtIndex(0)
self.titles.removeAtIndex(0)
2016-07-30 21:44:26.613 UITableViewLearn[14976:575144] *** 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, 2 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
UIKit在調用deleteRowsAtIndexPaths
時,會判斷前後數據源的一致性,如果前後不一致,會拋出異常。然而只是判斷cell的個數是否一致。如果刪除了第0、1列的數據,然後刪除第2、3列的cell,也不會報錯。
let indexPath = NSIndexPath.init(forRow: 2, inSection: 0)
let indexPath1 = NSIndexPath.init(forRow: 3, inSection: 0)
//title是數據源
self.titles.removeAtIndex(0)
self.titles.removeAtIndex(0)
self.tableView?.deleteRowsAtIndexPaths([indexPath,indexPath1], withRowAnimation: .Left)
上面的不會報錯
簡單插入
同樣是先插入數據,再插入cell。self.titles.insert("insert", atIndex: 1) self.tableView?.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
同時刪除和插入
beginUpdates()
調用deleteRowsAtIndexPaths
, insertRowsAtIndexPaths:
等方法
調用endUpdates
方法
對indexPath進行操作的次序
beginUpdates()
和endUpdates
之間的部分)中,所有的插入和選擇操作都發生在刪除操作之後
刪除和reload操作的指定的indexpath是原來tableView(未發生動畫之前)的indexPath
插入操作指定的indexPath是前面代碼執行完成以後的新tableView的indexPath。