删除NSMutableSet核心数据中的对象
问题描述:
我在使用核心数据删除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;
}
答
通常,当您需要删除或从表视图中删除元素,你需要执行两个步骤操作:
- 处理模型
- 处理表动画
您只执行了第一部分。要完成你需要这是不执行像下面
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
你需要,如果你执行多个动画为您的表来包装deleteRowsAtIndexPaths:withRowAnimation:
beginUpdates
和endUpdates
之间,例如,删除,修改等通话情况下,但你可以做到这一点。
当您使用核心数据时,您可以免费获得此代码(您必须编写一些代码)NSFetchedResultsController
及其代表NSFetchedResultsControllerDelegate
。因此,当您通过deleteObject
呼叫(步骤1)删除某个元素时,代表将自动响应该更改并执行步骤2.
请看How to use NSFetchedResultsController以了解如何正确设置它。
上面代码中的解决办法是使用
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
希望有所帮助。
嗨,我的NSFetchedResults控制器设置基本相同。因为我在构建此应用程序时使用了该示例。我真的不知道你的答案,但是我的代码的哪部分出错 – Luke 2012-07-08 14:48:53
我改变了我的代码上面,应用程序将删除对象,但它重新加载tableview时崩溃... – Luke 2012-07-08 15:01:43
你有没有试图把我提供的代码而不是重新加载表视图数据?这次事故是否和以前一样? – 2012-07-08 15:03:06