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