Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData merge conflict shows managed object version change not data

I am have an entity in core data and I try to update it from two different context. I am storing managedObjectID of my managed object which I need to update as it is thread safe. Before updating my object I refresh the object to avoid merge conflict. Here is my code:

context1.performBlock {
    let myObject = context1.objectWithID(managedObjectId)
    context1.refreshObject(myObject, mergeChanges: true)
    myObject.property1 = newValue
}

Notice that I haven't saved the context here, as I want to commit these changes as part of transaction with other updates.

For the same object I have some other properties which I need to commit straight away, so I create separate context for that to prevent property1 to get committed immediately.

context2.performBlock {
    let myObject = context2.objectWithID(managedObjectId)
    context2.refreshObject(myObject, mergeChanges: true)
    myObject.property2 = newValue
    do {
        try context2.save()
    }
    catch {}
}

In above code, on context2, I have updated property2, which will be committed to db immediately but this is not so frequent update in my case. On context1 I am updating property1 frequently (in every1 sec), and I commit it in every 10 seconds (notice that every time I update property1, I refresh object, so I will get updated value of property2 once changed by context2).

This works fine for most of the time, but some times I get merge conflict. I don't know why I am getting merge conflict even after refreshing object every time.

Also my console shows me same object except version of managed object, so if all properties are same than how version got updated?

Console log:

Error Domain=NSCocoaErrorDomain Code=133020 "Could not merge changes." UserInfo={conflictList=( "NSMergeConflict (0x17fa78f0) for NSManagedObject (0x18751830) with objectID '0x170f1ca0' with oldVersion = 8 and newVersion = 9 and old object snapshot = {\n property1 = value1;\n property2 = value2\n} and new cached row = {\n property1 = value1;\n property2 = value2\n}" )}

As you can see, older object snapshot and new cached row has same data, but version is different.

like image 978
Kapil Choubisa Avatar asked Feb 07 '23 03:02

Kapil Choubisa


1 Answers

As mentioned by @Husam in comment, try to set MergePolicy on ManagedObjectContext as:

 managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

Hope this help!

like image 54
D4ttatraya Avatar answered Feb 13 '23 05:02

D4ttatraya