![](https://img-blog.csdnimg.cn/img_convert/d0d564e40aa676847db59c619651ac04.png)
背景:
使用UITableView,删除行的时候程序崩溃,删除行的代码
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
排查原因
可能原因一:删除行的时候,tableview会再走一遍numberOfRowsInSection,如果不在数据源中删除数据,会造成数据的数量与row的数量不匹配造成程序崩溃。
![](https://img-blog.csdnimg.cn/img_convert/a734b4a6682f9857c947213702e8f002.png)
可能原因二:如果已经加了删除数据源的代码那可能就是另外一个原因,tableview的行数被写死了,当有行被删除时,行数不变,但是tableview的行数已经减1,造成两者数量不匹配,程序崩溃。
![](https://img-blog.csdnimg.cn/img_convert/c740c0ba0628117a26c58315634c0ba4.png)
归根结底还是行数设置错误。
解决办法
针对问题一,在该代码段中加入修改数据源的代码
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//加入下行代码
[self.dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
如果是问题二造成的,将tableview的行数设置成数据源的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataArray.count;
}