Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An NSManagedObjectContext cannot delete objects in other contexts

Tags:

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?

like image 362
cetcet Avatar asked May 02 '11 23:05

cetcet


2 Answers

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:

  • Have a shared reference to the same 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.

like image 145
dominostars Avatar answered Oct 11 '22 06:10

dominostars


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.

like image 32
Andrew Eades Avatar answered Oct 11 '22 06:10

Andrew Eades