Reputation: 3658
I use concurrency in Core Data. Apple docs like this often told me that synchronization of the contexts depends on the semantics of my application. And I can't found concrete samples how to merge UIManagedObjectContext
s.
So in my app one UIManagedObject
may have different property values in different contexts. I need to merge contexts by replacing objects or updating its properties.
Here's my code:
- (void)__saveToMainContext
{
if ([_context_ hasChanges])
{
NSError *error = nil;
if (![_context_ save:&error])
{
if (error.code == NSManagedObjectMergeError)
{
for (NSMergeConflict* conflict in [[error userInfo] objectForKey:@"conflictList"])
{
[_context_ refreshObject:[conflict sourceObject] mergeChanges:YES];
}
}
}
}
}
But this method creates duplicates objects.
Upvotes: 1
Views: 944
Reputation: 3706
In theory, you should just pick up the merge policy you prefer and set it in the NSManagedObjectContexts, like the doc says.
You will be able to decide whether to keep the local changes, the storage once and so on:
enum {
NSErrorMergePolicyType = 0x00,
NSMergeByPropertyStoreTrumpMergePolicyType = 0x01,
NSMergeByPropertyObjectTrumpMergePolicyType = 0x02,
NSOverwriteMergePolicyType = 0x03,
NSRollbackMergePolicyType = 0x04
};
But I guess you already know this things. Once I wrote an category to more easily handle those circumstances, you can find the implementation code here. I myself found part of it somewhere in the cyberspace, but I can't find it back now and thus I cannot cite the other author.
BUT my seggestion is always: avoid handling this manually. It's a real pain in the ass. I found really comfortable using MagicalRecord for CoreData management, it works like a charme.
Upvotes: 1