I am encountering an issue when attempting to remove an object from my Core Data store. The error I receive when calling deleteOject is as follows: An NSManagedObjectContext cannot delete objects in other contexts.
I have found some documentation regarding this error online but it mostly relates to accessing the ManagedObjectContext in multiple threads which can cause issues, but I am not currently working on any other threads. I have gone through my code in an attempt to ensure that I am not creating any other context except for the one that I create in my AppDelegate and can not find a likely culprit.
The code that I am testing with is below:
NSMutableSet *remoteNids = [NSMutableSet setWithObjects:@"140", @"141", nil];
for (GCEvent *event in nodeEventsFromStore) {
if (![remoteNids containsObject:event]) {
NSLog(@"Event no longer exists on remote. Removing object %@ from store.", event);
[[delegate managedObjectContext] deleteObject:event];
}
else {
NSLog(@"Event %@ exists on remote", event);
}
}
It’s highly unlikely that Core Data is lying to you. I would suggest putting an assert in your code like this:
Run your app via Xcode with breakpoints on (so it breaks when you hit the assertion) and set MallocStackLoggingNoCompact=YES.
When the assert is triggered, you can use the gdb console like so:
That will print the alloc stack trace and show you where you created the two moc’s.