【问题标题】:UITableView crashes when pressing delete button in edit mode在编辑模式下按下删除按钮时 UITableView 崩溃
【发布时间】:2013-04-20 23:39:58
【问题描述】:

在编辑 UITableView 时,应用程序通常会在有人按下 uitableviewcell 上的“删除”按钮后崩溃并显示此错误。这通常发生在表格视图中的第一个项目上,但也发生在其他项目上。我很抱歉如此含糊,我可以提供任何额外的信息。我只是对为什么会发生这种情况以及为什么会发生这种情况感到非常困惑。

* 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object”

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
}

-(void)viewWillAppear:(BOOL)animated{
    [_matchIDS removeAllObjects];
    _matchIDS = [[NSMutableArray alloc]init];
    _matchIDS = [[NSUserDefaults standardUserDefaults] valueForKey:@"allMatchIDS"];
    [self.tableView reloadData];
}

-(void)viewWillDisappear:(BOOL)animated{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:_matchIDS forKey:@"allMatchIDS"];
    [defaults synchronize];
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = _matchIDS[indexPath.row];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_matchIDS removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

【问题讨论】:

    标签: ios xcode uitableview


    【解决方案1】:

    错误是由于试图从 _matchIDS 数组中删除一个元素而导致的,该数组是不可变的。

     [_matchIDS removeObjectAtIndex:indexPath.row];
    

    您尝试在此处使数组可变:

    -(void)viewWillAppear:(BOOL)animated{
        [_matchIDS removeAllObjects];
        _matchIDS = [[NSMutableArray alloc]init];
        _matchIDS = [[NSUserDefaults standardUserDefaults] valueForKey:@"allMatchIDS"]; // <---
        [self.tableView reloadData];
    }
    

    但上面标记的行替换了 _matchIDS,丢弃了您实例化的 NSMutableArray。您可能想改用 mutableCopy 方法,结果如下:

    _matchIDS = [[[NSUserDefaults standardUserDefaults] valueForKey:@"allMatchIDS"] mutableCopy];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2011-04-17
      相关资源
      最近更新 更多