Alex Rivera | Logout

Illegal attempt to establish a relationship 'xyz' between objects in different contexts

Asked 2009-10-12T13:35:32.470
47

I am using Apple's CoreDataBooks sample application as a basis for pulling data into a secondary managed object context in the background, and then merging that data into the primary managed object context.

The data I am pulling in is a Book entity with a to-one relationship with an Owner entity (called "owner"). The Owner entity has a to-many relationship with the Book (called "books").

My data is an XML document of the form:

<Owner>
  <Name>alexpreynolds</Name>
  <ID>123456</ID>
</Owner>
<Books>
  <Book>Book One</Book>
  <Book>Book Two</Book>
  ...   
  <Book>Book N</Book>
</Books>

Book One through Book N are associated with one Owner ("alexpreynolds, 123456").

I am parsing this into an Owner instance and an NSMutableSet made up of Book instances.

When I attempt to save the first time, it saves fine and the merged data shows up in the table view.

On the second save, however, when the XML content contains a new book, it doesn't work.

Here's what happens:

I then attempt to load in an XML document that contains a new Book not already in the primary managed object context. The new Book is using the same Owner as that which is associated with the other Books.

I have routines that pick out this unique Owner managed object (which I already have in my primary managed object context) and the unique Book that is not found in the primary MOC.

From this, I create a new Book object in the secondary MOC, and I set its "owner" relationship to point to the unique Owner I found in the primary MOC.

When I sa

Edit
Report

1 Answer

11

I had the same problem and this sentence helped me to solve the error.

You can't have relationships between objects in different managed object contexts. So one way of getting around that is to bring the object into the managed object context.

Here's my code (I replaced the variables to make it work for you):

// Have the owner object and get the managedObjectContext
Owner *owner = [[DataFunctions alloc] getCurrentOwner];
NSManagedObjectContext *context = [owner managedObjectContext]; 

// Create a book and use the manageObjectContext of owner
Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context];
[newQuote setValue: "Book Title" forKey:@"title"];
[newQuote setOwner:owner];

I hope this helps :)

answered 2013-02-25T18:46:14.707

Your Answer