I have two entities, each displaying on its own UITableView section.
I've enabled editing to allow the user to delete rows by swiping to the right. This works fine for the first entity, but when I try to delete an object in the second entity, I get this error:
An NSManagedObjectContext cannot delete objects in other contexts
I get what the error says, but I can't see how it applies here. I use a retained reference to my context to create, fetch, and delete all objects from the database, so I'm sure there's only the one context. I'm also not using multiple threads. Any idea what could be happening?
Is the context that you fetched the NSManagedObject
from, the same instance, as the context you're using to delete the NSManagedObject
? If not, you need to either:
NSManagedObjectContext
so that you delete the object from the same context that you created or fetched it from. If you're not using multiple threads, then you should only need to call [[NSManagedObjectContext alloc] init]
once ever in your code.or
If you have to use two different instances of NSManagedObjectContext
, then get the objectID
from the NSManagedObject
you got from the first context, so that you can later call:
[context deleteObject:[context objectWithID:aObjectID]];
The NSManagedObjectID
is the same between contexts, but the NSManagedObject
itself is not.
I use this:
func delete(object: YourManagedObject) { guard let context = object.managedObjectContext else { return } if context == self.viewContext { context.delete(object) } else { self.performBackgroundTask { context in context.delete(object) } } try? self.viewContext.save() }
Basically, it is quite likely that the object that you want to delete was provided by the viewContext of NSPersistentContainer. So trying to delete from the private background context won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With