I've been banging my head against the wall with this bug. Basically relationships aren't being merged from one context to another correctly.
Let's say I have two entity types in my model, Student and Teacher. A student can only have one teacher and a teacher can obviously have many students. I set this up correctly in my xcdatamodel class.
Because I'm syncing these entities from the server I have 2 Managed Object Contexts - one called uiContext
which has it its concurrency type set to NSMainQueueConcurrencyType
and another called backgroundContext
with its concurrency type set to NSPrivateQueueConcurrencyType
.
I've also set up a nested structure using [self.uiContext setParentContext:self.backgroundContext];
So this is what I'm doing:
1) Fetch Teachers from the server
2) Create managed objects for them in backgroundContext
3) Call save
on backgroundContext
4) I listen for the NSManagedObjectContextDidSaveNotification
, and execute the following code:
[self.uiContext performBlock:^(void) { [self.uiContext mergeChangesFromContextDidSaveNotification:notif]; }];
So far this works just fine. My uiContext gets the Teacher managed objects and my UI updates accordingly.
It breaks down though when I do the following:
5) Fetch the student data from the server
6) Create managed objects for them in the backgroundContext
and set the relationship from student to the appropriate teacher.
7) Call save
on backgroundContext
8) Since I'm listening for the NSManagedObjectContextDidSaveNotification
notification this save should get merged into the uiContext
However, here's where I start experiencing issues. Even though the student objects are merged into the uiContext
correctly, the relationship from teacher to student is not set. The relationship from student to teacher is correctly set but not the other way around. Specifically, [someTeacherObject.students count] == 0
but someStudentObject.teacher != nil
The relationships are set correctly in both the backgroundContext
and the persistent store (verified). Just not in the uiContext
.
Any ideas what could be going on? Any idea how to better debug this?