报错信息:reason: '* -[__NSArrayM objectAtIndex:]: index 12 beyond bounds [0 .. 11]'
删除8行之后就会报错 是什么原因?
代码
-(NSMutableArray *)dataList{
if (_dataList ==nil) {
_dataList=[NSMutableArray array];
for (int i =0; i<20; i++) {
NSString *numberString =[NSString stringWithFormat:@"%d",arc4random_uniform(100000)];
[_dataList addObject:numberString];
}
}
return _dataList;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
NSString *numberString = self.dataList[indexPath.row];
cell.textLabel.text =numberString;
return cell;
}
#pragma mark - cell编辑
-
(nullable NSArray <UITableViewRowAction >)tableView:(UITableView )tableView editActionsForRowAtIndexPath:(NSIndexPath )indexPath {
UITableViewRowAction *action3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) { [self.dataList removeObjectAtIndex:indexPath.row]; [_tableView reloadData]; }]; NSArray *actionArray = @[action3]; return actionArray;
}
你看看你这里面写死了20,你
self.dataList
总共20个,删除了8个之后就只剩下了12个了,你在reload的时候,tableview计算第12个cell的时候(0-12),NSString *numberString = self.dataList[indexPath.row];
,从数组中取第12个,但是你数组里面总共是0-11个,这不数组越界了嘛。所以你这不能写死,要改成这样:
另外再补充一句,一般来说,如果只是删除,不涉及到其他变动的话,没必要全部reload,只需要reload从删除那行及其以下的位置,这样可以节约一些不必要的性能浪费。