koen
koen

Reputation: 5729

Change relationship of NSManagedObject to different context

This is a follow up to an earlier question: Core Data: change delete rule programmatically.

I'd like to rephrase my question, and will do that here.

Briefly, my app allows updating entries from a 3rd party database, but I'd like to keep user annotations. So my workflow is:

  1. iterate over all entities
  2. download external xml and parse it into a new entity
  3. if user annotations, change their relationship from old entity to new entity
  4. delete old entity

During the import, the old entity is in the main context, the new entity is in a temporary import context. Number 3 gives me problems, if I just change the relationship, then they don't show if I update my UI. If I use the objectID to get the annotation and then change the relationship as follows:

    NSManagedObjectID *objectId = oldAnnotation.objectID;
    Annotation *newAnnotation = [importContext objectWithID: objectId];
    [newEntry addAnnotationObject: newAnnotation];

It's still not working - it's not showing up.

EDIT: if I change the context in the second line to newEntry.managedObjectContext, I get an Illegal attempt to establish a relationship 'foo' between objects in different contexts error.

What am I missing?

UPDATE: After some late-night hair-pulling debugging, I found that I when I was fetching the newEntry, I was actually fetching the oldEntry, therefore none of the changes would show up. The answer below by @Mundi pointed me in the right direction.

Copying the old annotations worked using my code above, followed by copying the attributes. For some user input with relationships in itself, I had to do a "Deep Copy", which I found here: How can I duplicate, or copy a Core Data Managed Object?.

Upvotes: 0

Views: 650

Answers (1)

Mundi
Mundi

Reputation: 80265

I think creating a new entity and deleting the old one is a problematic strategy. You should try to properly update the existing entities and only create new ones if they do not yet exist.

Whenever I need an object from a different context, I fetch it. That being said, your object id code should work. However, there could be all sorts of other glitches, that you should check:

  • Did you save the importContext?
  • Did you save its parent context, presumably the main context?
  • Was the modified object graph saved to the persistent store?
  • Are you checking the results after you have saved?

Upvotes: 1

Related Questions