从表格视图中删除一行

问题描述:

当我试图从表格视图中删除一行时,我遇到了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]; 
} 
+0

你可以显示你的代码为'tableView:numberOfRowsInSection:'? – jonkroll 2012-03-27 18:20:32

+0

我已更新原始帖子以显示section方法中的行数,并显示尝试在编辑后返回正确数量的行,但不幸的是得到相同的结果。 – dmeads89 2012-03-27 21:13:29

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section方法可能不会返回行的相应数量的行数无效。它应该返回以前的行数减去刚删除的行数。

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

+0

我已更新原始帖子以显示节方法中的行数,并显示尝试在编辑后返回正确数量的行,但不幸的是得到相同的结果。 – dmeads89 2012-03-27 21:14:59

您需要包括

[tableView beginUpdates]; 

[tableView endUpdates]; 

在你的代码。这两种方法可以防止UITableView在删除或插入行时崩溃。

beginUpdates放在你删除tableView的行之前,然后endUpdates一旦你完成了。

这是documentation

+0

仍是同样的问题。我认为我的实施可能有一些问题,你的回答是正确的。谢谢。 – dmeads89 2012-03-27 23:11:23

[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]; 

这对我来说是最后的工作。