0

When editing the UITableView, the app usually crashes with this error after someone presses the "delete" button on the uitableviewcell. This usually happens for the first item in the table view, but has happened to others. I'm sorry for being so vague, I can provide any additional infomation. I'm just very confused on why this happens and why it happens when it does.

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__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];
    }
}
4

1 回答 1

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];
于 2013-04-21T00:11:33.860 回答