ios - 删除tableview行的错误

查看:141
本文介绍了ios - 删除tableview行的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

报错信息: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个,这不数组越界了嘛。

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}

所以你这不能写死,要改成这样:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

另外再补充一句,一般来说,如果只是删除,不涉及到其他变动的话,没必要全部reload,只需要reload从删除那行及其以下的位置,这样可以节约一些不必要的性能浪费。

这篇关于ios - 删除tableview行的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆