- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"%@",context);
// Delete object from database
[context deleteObject:[self.devices objectAtIndex:indexPath.row]];
NSLog(@"%@",context);
NSError *error = nil;
if (![context save:&error]) {enter code here
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.devices removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
错误是NSManagedObjectContext无法删除其他上下文中的对象
答案 0 :(得分:1)
用于获取NSManagedObject的NSManagedObjectContext实例与当前实例不同。
另请检查:An NSManagedObjectContext cannot delete objects in other contexts
答案 1 :(得分:0)
您必须使用与通过调用self.devices
返回的NSManagedObjectContext不同的NSManagedObjectContext获取与[self managedObjectContext]
关联的数组中的对象。您尝试删除的对象无法使用不同的上下文进行更改或操作,这就是您收到错误的原因。
你可以尝试做什么,如果要删除该对象,请将其拉出然后删除/更改对象,如下所示:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context;
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"%@",context);
// Delete object from database
MyObject *object = [self.devices objectAtIndex:indexPath.row];
context = object.managedObjectContext;
[context deleteObject:object]
NSLog(@"%@",context);
NSError *error = nil;
if (![context save:&error]) {enter code here
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.devices removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
这将适用于您的情况,但您应该如何使代码更容易使用NSFetchedResultsController。以下是一些有关如何使用它的有用链接:
http://www.raywenderlich.com/999/core-data-tutorial-for-ios-how-to-use-nsfetchedresultscontroller https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/index.html