Reputation: 40437
Consider the following code:
[context performBlock:^{
// add a bunch of objects to context
NSError *error;
if(![context save:&error])
NSLog(@"Couldn't save MOC because of error: %@", error.localizedDescription);
}];
This is inside a "Store Manager" class, which has getters for 2 MOCs: a standard .objectContext
and a .backgroundObjectContext
, which is initialized with the following:
backgroundObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
backgroundObjectContext.parentContext = self.objectContext;
My problem: when I set context
to self.objectContext
, everything is fine and the data is saved to the .sqlite file. When I set it to self.backgroundObjectContext
, no data is written to the sqlite file, but save:
returns YES
with no error. I tried logging that context's registeredObjects
and everything is there. How come the data doesn't get written to the sqlite file?
I've been using the new MOC iOS 5 APIs for a while and this is the first time I'm encountering this issue, so I'm pretty clueless. Is that how you initialize a background MOC in iOS 5? Is there anything else I might be missing here?
Upvotes: 0
Views: 478
Reputation: 289
When you save a childContext, changes are merged with the parentContext. To be written to a file, you need to save the context at the root.
So in this case:
you save backgroundObjectContext to merge changes with objectContext
you save objectContext to save to the PSC
Upvotes: 3