向UITableView添加行时出现问题

时间:2014-03-29 22:20:23

标签: ios objective-c uitableview

我正在尝试将单元格添加到UITableView而不重新加载表格。我已经能够添加一个对象,但如果我删除一个对象,然后尝试添加另一个对象,它就不起作用,我得到下面列出的错误消息。这是我用来添加行和删除行的代码:

添加一行:

-(void)addSelected:(UIButton *)sender {

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.periodArray.count inSection:0];

    [self.classTableView beginUpdates];
    NSLog(@"Previous Period count: %lu", (unsigned long)self.periodArray.count-1);
    [self.periodArray addObject:@"Period 8"];
    NSArray *newResults = [NSArray arrayWithObjects:indexPath, nil];
    [self.classTableView insertRowsAtIndexPaths:newResults withRowAnimation:UITableViewRowAnimationNone];
    [self.classTableView endUpdates];
    self.classTableView.frame = CGRectMake(0, 0, 320, 44*[self.periodArray count]+63);
}

要删除:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    [self.classTableView beginUpdates];
    [self.periodArray removeObjectAtIndex:indexPath.row];
    [self.classTableView deleteRowsAtIndexPaths: @[ indexPath ] withRowAnimation: UITableViewRowAnimationAutomatic];
    NSLog(@"Period count after delete: %lu", (unsigned long)self.periodArray.count);
    [self.classTableView endUpdates];
}

错误讯息:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 5]'

1 个答案:

答案 0 :(得分:0)

在 之后从基础数组 中删除您的行,将其从表中删除。

那是:

[self.classTableView deleteRowsAtIndexPaths: @[ indexPath ] withRowAnimation: UITableViewRowAnimationAutomatic];
[self.periodArray removeObjectAtIndex:indexPath.row];

你应该好好去。