ios 解决bug---UITableView删除到最后一个unable to generate a new section map with old section count: 1 and new

本文介绍了一个在iOS应用中使用UITableView进行分组删除时遇到的问题及解决方案。当尝试删除最后一行时,会触发异常错误。文章提供了一段修改后的代码示例,确保在删除最后一项时正确更新section。

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

在iOS的UItableview删除中,删除操作我们经常用这样的语句
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
      
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
        
    }  
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
    
}


但是每次删除到最后一行时就会报错,报错提示是这样的:

 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView internal bug: unable to generate a new section map with old section count: 1 and new section count: 0'




这是因为 tableView 是分组的,删除最后一个分组中最后一个cell 和数据源时 也要对 session 进行操作

正确的处理方法为:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView beginUpdates];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
     
       
       
         [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
        }
       [tableView reloadData]; 
   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
       
    }
    [tableView endUpdates];
}


在这里我加入了 
 [tableView beginUpdates];
 [tableView endUpdates];
并且还需要对最后一个section做删除操作

 [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值