toofah
toofah

Reputation: 4475

Core Data: Illegal attempt to establish relationship + (null) context

I am parsing data on a background thread, inserting new entities and setting up relationships with other existing entities.

Sometimes I get the error: 'attempting to establish relationship between objects in different contexts'.

After reading more about this I am now creating a new ManagedObjectContect in my background thread and using it to insert the new entities and setup the relationships. I am careful to only use this new ManagedObjectContext in my background thread. When I need to find an existing entity to setup a relationship between an existing object and one of these new objects, I call [moc objectWithId:id] to fetch the existing object using my new moc. However, I am still getting the error.

Frustrated, I started printing things out. I noticed that when I print out the managedObjectContext property for each NSManagedObject, just before setting up the relationship, I sometimes get '(null)' printed out. This seems to be when the problem occurs.

Can anyone tell me what I am doing wrong? Why do I sometimes have (null) mocs on my objects?

Thanks for any help you can give!

Upvotes: 1

Views: 575

Answers (3)

TechZen
TechZen

Reputation: 64428

The most likely explanation is that you are trying to link to objects created in one context that have not been merged with the other context. No changes made in one context will show up in another until the context have been merged. That is what your error message is telling you.

The Null object is most likely caused by using temporary objectIDs. An objectID is not fixed until the object has been saved to the persistent store. Until then it has a temporary ID which will change when it is saved.

Upvotes: 1

Jonathan
Jonathan

Reputation: 1602

The NSmanagedObject has a method called isInserted, this confirms if an object has been inserted into a managedObjectContext check this value, if it is no use the insert method on NSManagedObjectContext to insert it.

Upvotes: 0

Rog
Rog

Reputation: 18670

We need to see some of your code. My first thought would be to check whether you're accessing the managedObjectContext via its property or directly?

Accessing it via property will make sure the context is always available (i.e. not nil) when creating new managed objects, provided you are using the template core data methods provided by Apple.

Upvotes: 0

Related Questions