2012-07-07 54 views
0

我在使用核心数据删除NSMutableSet中的对象时遇到问题。我想在我的tableview的第二部分中删除一个“player”对象。我收到错误;删除NSMutableSet核心数据中的对象

无效更新:在第1行的无效数(6)的包含在现有部分中的更新后的行 数必须 等于包含在该部分的行数的 更新之前(6),加或减从 插入或删除的行数(0插入,1删除)和正或负数 行移入或移出该部分(0移入,0移出

解决方案

看看我的代码。

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


     if (indexPath.section==0) { 

     }else{ 

      _player = [self.fetchedResultsController.fetchedObjects objectAtIndex: indexPath.row]; 
      [self.managedObjectContext deleteObject:_player]; 
      [self performFetch]; 
      [self.managedObjectContext save:nil]; 

      // here the solution to make it works... 
      [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];    
     }    
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    switch(section){ 
     case 0: 
      return 4; 
     case 1: 
      return [self.fetchedResultsController.fetchedObjects count]; 
    } 
    return 0; 
} 

回答

1

通常,当您需要删除或从表视图中删除元素,你需要执行两个步骤操作:

  1. 处理模型
  2. 处理表动画

您只执行了第一部分。要完成你需要这是不执行像下面

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

你需要,如果你执行多个动画为您的表来包装deleteRowsAtIndexPaths:withRowAnimation:beginUpdatesendUpdates之间,例如,删除,修改等通话情况下,但你可以做到这一点。

当您使用核心数据时,您可以免费获得此代码(您必须编写一些代码)NSFetchedResultsController及其代表NSFetchedResultsControllerDelegate。因此,当您通过deleteObject呼叫(步骤1)删除某个元素时,代表将自动响应该更改并执行步骤2.

请看How to use NSFetchedResultsController以了解如何正确设置它。

上面代码中的解决办法是使用

[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade]; 

希望有所帮助。

+0

嗨,我的NSFetchedResults控制器设置基本相同。因为我在构建此应用程序时使用了该示例。我真的不知道你的答案,但是我的代码的哪部分出错 – Luke 2012-07-08 14:48:53

+0

我改变了我的代码上面,应用程序将删除对象,但它重新加载tableview时崩溃... – Luke 2012-07-08 15:01:43

+0

你有没有试图把我提供的代码而不是重新加载表视图数据?这次事故是否和以前一样? – 2012-07-08 15:03:06

相关问题