iOS調(diào)用reloadRowsAtIndexPaths Crash報(bào)異常NSInternalInconsiste

背景

在更新 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];)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容