删除tableview行的错误

发布于 2022-09-02 15:15:24 字数 1521 浏览 11 评论 0

报错信息: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;

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

子栖 2022-09-09 15:15:24

你看看你这里面写死了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从删除那行及其以下的位置,这样可以节约一些不必要的性能浪费。

甩你一脸翔 2022-09-09 15:15:24

楼上正解,已经很全面了,另外说一下要学会看错误信息reason: '* -[__NSArrayM objectAtIndex:]: index 12 beyond bounds [0 .. 11]',一看就是数组越界了

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文