CloudKit, 2 quick saves, error: "Could not merge changes"

I'm experimenting with Core Data and CloudKit using the recommended `NSPersistentCloudKitContainer`. I'm kind of new to Core Data so maybe I'm doing something simple/stupid. I get an error when changing the object twice, quickly.


I have a SwiftUI view of one of my managed objects, with button toggle the "isActive" property. If I tap it twice in a row, I get an error from `NSManagedObjectContext.save`. How do you prevent or recover from this kind of error?


It seems to be a timing thing, because I'm having trouble duplicating it.


private func toggleActiveState() {
    exercise.isActive = !exercise.isActive
    try! moc.save() // error
}


Rob


Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=133020 "Could not merge changes." UserInfo={conflictList=(

"NSMergeConflict (0x282fb15c0) for NSManagedObject (0x2819ca8a0) with objectID '0xb61bc172bb432131 <x-coredata://6C618B32-5866-4E35-93C9-3B7F3D221FE6/MyObject/p7>' with oldVersion = 4 and newVersion = 5 and old object snapshot = {\n isActive = 0;\n mostRecentEvent = \"<null>\";\n name = \”Foo\”;\n notes = \"<null>\";\n} and new cached row = {\n isActive = 0;\n mostRecentEvent = \"<null>\";\n name = \”Foo\”;\n notes = \"<null>\";\n}"

), NSExceptionOmitCallstacks=true}:

Answered by rnikander in 424433022

I haven't this problem since I found the sample project under "Synchronizing a Local Store to the Cloud" and copied the setup code there. In the file CoreDataStack.swift there are a few lines that setup merge policy. I'm guessing that was my problem.

Accepted Answer

I haven't this problem since I found the sample project under "Synchronizing a Local Store to the Cloud" and copied the setup code there. In the file CoreDataStack.swift there are a few lines that setup merge policy. I'm guessing that was my problem.

CloudKit, 2 quick saves, error: "Could not merge changes"
 
 
Q