ios - 删除tableview行的错误
迷茫
迷茫 2017-04-17 17:59:30
0
2
218

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

    }

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
迷茫

Look at the number 20 written in here. You self.dataList总共20个,删除了8个之后就只剩下了12个了,你在reload的时候,tableview计算第12个cell的时候(0-12),NSString *numberString = self.dataList[indexPath.row]; take the 12th number from the array, but the total number in your array is 0-11. Isn’t this an array out of bounds?

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

So you can’t write this to death, you have to change it to this:

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

In addition, generally speaking, if it is just deletion and no other changes are involved, there is no need to reload everything. You only need to reload the deleted row and the following positions, which can save some unnecessary waste of performance.

迷茫

The correct answer upstairs is very comprehensive. In addition, you should learn to read the error message reason: '* -[__NSArrayM objectAtIndex:]: index 12 beyond bounds [0 .. 11]'. At first glance, it means that the array is out of bounds

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!