I’m using the new iOS 5 core data concurrency options. I have two threads:
mainContext: NSMainQueueConcurrencyType
backgroundContext: NSPrivateQueueConcurrencyType, parent = mainContext
I have an object called squareObject which is currently fetched and owned by the main context. I modify a property of this object, say
squareObject = [getSquareObjectForContext:mainContext];
squareObject.isPendingChange = [NSNumber numberWithBool:YES];
Then I save this context. Now, I execute a fetch on the backgroundContext:
[backgroundContext performBlock^{
...
pendingSquares = [[appDelegate.serverMOC executeFetchRequest:fetchRequest error:&error] mutableCopy];
[pendingSquares filterUsingPredicate:[NSPredicate predicateWithFormat:@"isPendingChange == YES"]];
}];
However, I do get items back, but none of them have the new value of 1 for isPendingChange.
Why have the changes not propagated to the backgroundContext? According to the documentation:
Changes you make to a managed object in one context are not propagated
to a corresponding managed object in a different context unless you
either refetch or re-fault the object.
So I did refetch, but the changes were not committed. And I don’t think I really need to save the mainContext after making changes for them to appear in the backgroundContext, right?
If the square object is owned by the backgroundContext, then everything works fine:
squareObject = [getSquareObjectForContext:backgroundContext];
squareObject.isPendingChange = [NSNumber numberWithBool:YES];
Obviously, these changes appear when I fetch in the backgroundContext since the changes were made on that context. I’m just not understanding why the child context is unable to fetch changes made by the parent context using a brand new fetch request. I thought this was the way to do it?
This assumption is incorrect. You do have to save the child context for the changes to appear in the parent context.
But when you save the parent context, it automatically triggers saving child context first.
This is because changes are propagated from child to parent, not the other way around.