首页 > 删除tableview行的错误

删除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编辑

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


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

【热门文章】
【热门文章】