关于UITableView调用deleteRowsAtIndexPaths程序崩溃的问题

当尝试通过UITableView的deleteRowsAtIndexPaths方法实现侧滑删除功能时,遇到程序崩溃问题。错误提示表明在删除最后一个元素时,数据源未同步更新。解决办法是避免直接调用deleteRowsAtIndexPaths,而是使用beginUpdates和endUpdates方法来确保数据源和视图同步更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景:在使用UITableView时,我为了达到可以侧滑点击删除的效果,调用了deleteRowsAtIndexPaths方法,结果导致程序崩溃。

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    [_bookModel.markArr removeObject:markModel];
}

错误提示:

*** 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 (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

原因:0.0 自己英语不好,但根据错误提示可以看到崩溃的原因和section有关。
后来在网上查资料,找到了崩溃的原因:
- 在section中,删除了最后一个row的时候,而section依然存在,并没有删除。
解决办法:不调用deleteRowsAtIndexPaths方法,调用reload方法

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [_bookModel.markArr removeObject:markModel];
    [_tabView reloadData];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值