gpt4 book ai didi

ios - 从 managedObjectContext 中删除 NSManagedObject

转载 作者:行者123 更新时间:2023-11-29 02:03:55 25 4
gpt4 key购买 nike

我有一个 UITableViewController 设置,它在加载时正确显示我的 managedObjects,但是当我去删除一个单元格时,我的应用程序崩溃了。这是控制台必须说的:

    2015-05-03 09:55:20.125 MyApp[9461:663817] *** Terminating app due to 
uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update:
invalid number of rows in section 0. The number of rows contained in an existing
section after the update (1) must be equal to the number of rows contained in
that section before the update (1), plus or minus the number of rows inserted or
deleted from that section (0 inserted, 1 deleted) and plus or minus the number of
rows moved into or out of that section (0 moved in, 0 moved out).'

当我重新启动应用程序并转到我的 TVC 时,我上次删除的对象被删除了。

我在 NSFetchedResultsController 中设置了一些部分,这些部分在调用 viewDidLoad 时实例化。我怀疑我有一个小问题,但我不确定去哪里添加缺失的行?

我使用这一行在 viewDidLoad 中启用滑动删除:

// Enable swipe to delete
self.tableView.allowsMultipleSelectionDuringEditing = NO;

这是我的commitEditingStyle:

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete selected NSManagedObject from managedObjectContext
NSManagedObject *objectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.managedObjectContext deleteObject:objectToDelete];
[self.managedObjectContext save:nil];


// Delete the row from the data source
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}

感谢阅读。如果您有任何想法,欢迎提出。

最佳答案

错误消息表明从 numberOfRowInSection 返回的行数与表中当前项目数不匹配。当你使用 fetchedResultsController numberOfRowsInSection 应该看起来像这样。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self.fetchedResultsController fetchedObjects] count];
}
然后自动调用

fetchedResultsController 委托(delegate) didChangeObject: ,它会调用内部的 deleteRowAtIndexPaths: ..所以你不需要调用deleteRowAtIndexPaths:只需调用 deleteObject否则它会删除两次。

关于ios - 从 managedObjectContext 中删除 NSManagedObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com