Search code examples
ioscore-datansmanagedobjectcontext

Cannot delete objects in other context


I am facing this problem consistently for over 3 months. I have searched a lot and read related docs and visited many forums but couldn't find working solution. I am getting typical NSManagedObject error while deleting objects. An NSManagedObjectContext cannot delete objects in other contexts.

I tried to go around and tried to delete object using its NSManagedObject ID but to no avail.

  NSManagedObjectID *findingsSurveyDataItemApiId = [findingsSurveyDataItemApi objectID];
            [self.managedObjectContext deleteObject:[self.managedObjectContext objectWithID:findingsSurveyDataItemApiId]];

Can anyone tell why is above solution still not working?

PS: I have two managed object context in the app.


Solution

  • I guess it might be a misleading error message from Core Data. If the object you want to delete has not yet been saved to the persistent store, objectWithID will not return a valid object, according to the docs:

    The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired).

    Use existingObjectWithID:error: instead and check if it returns a non-nil object before trying to delete it.