背景
在更新 TableView 的時候調(diào)用[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];crash掉了轩拨,報異常attempt to delete row 0 from section 0 which only contains 0 rows before the update
原因
在調(diào)用reloadRowsAtIndexPaths時唐瀑,依賴于tableView先前的狀態(tài)已有要更新的cell洛退,它內(nèi)部是先刪除該cell伊脓,再重新創(chuàng)建怔檩,所以當(dāng)你在原先沒有該cell的狀態(tài)下調(diào)用reloadRowsAtIndexPaths壁畸,會報異常你正在嘗試不存在的cell阀趴。
簡言之氢架,如果你要改變tableView的cell數(shù)量碌尔,就不要調(diào)用更新局部的cell方法浇辜。
解決辦法
1.使用reloadData
reloadData是完全重新加載券敌,包括cell數(shù)量也會重新計算,不會依賴之前tableView的狀態(tài)柳洋。
2.使用beginUpdates和 endUpdates(未自驗證待诅,驗證者可留言)
當(dāng)你在將要更改cell數(shù)量的時候都要通知tableView更新(調(diào)用[tableView beginUpdates];)
添加時通知使用方法(void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
移除時通知使用方法 (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
當(dāng)你已經(jīng)更改cell數(shù)量的時候都要告訴tableView更新完畢(調(diào)用[tableView endUpdates];)