【问题标题】:deleting a row out of table view从表视图中删除一行
【发布时间】:2012-03-27 18:14:24
【问题描述】:

当我尝试从表视图中删除一行时,我的tableView 崩溃了。该方法被正确调用,因为在数据库中正确进行了更改。我收到的错误是:

无效更新:第 0 节中的行数无效。

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

    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [delegate managedObjectContext];


    NSManagedObject *objectToDelete = [fixedArray objectAtIndex:indexPath.row];

    [context deleteObject:objectToDelete];

    [delegate saveContext];

    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    fixedArray = ([self mondayData]); // this is fetching the data for the array that I supply to the table view

[self.tableView numberOfRowsInSection:[fixedArray count]];

    [self.tableView reloadData];


}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [fixedArray count];
}

【问题讨论】:

  • 你能出示tableView:numberOfRowsInSection:的代码吗?
  • 我已经更新了原始帖子以显示 section 方法中的行数,并显示我在编辑后返回正确行数的尝试,但不幸的是结果相同。

标签: iphone ios uitableview core-data


【解决方案1】:

您的- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 方法可能没有返回适当数量的行。它应该返回之前的行数减去刚刚删除的行数。

此外,如果该部分中没有更多行,则必须从 UITableView 中删除该部分。

【讨论】:

  • 我已经更新了原始帖子以显示 section 方法中的行数,并显示我在编辑后返回正确行数的尝试,但不幸的是结果相同。
【解决方案2】:

你需要包含

[tableView beginUpdates];

[tableView endUpdates];

在您的代码中。这两种方法将防止UITableView 在您删除或插入行时崩溃。

在删除 tableView 的行之前输入beginUpdates,然后在完成后输入endUpdates

这是documentation

【讨论】:

  • 还是同样的问题。我认为我的实现可能有很多问题,你的回答是正确的。谢谢。
【解决方案3】:
    [tableView beginUpdates];

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];


        NSManagedObject *object = [fixedArray objectAtIndex:indexPath.row];

        [object setValue:@"No" forKey:@"selected"]; // this works and persists into the database

        [delegate saveContext];

        fixedArray = ([self mondayData]);

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];

    }


    [tableView endUpdates];

    [self.tableView reloadData];

这最终对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多