Common Core Data Issues

While using Core Data with swift and swiftui I've ran into a few gotchas. This page documents those and how I fixed them.

Merge Conflicts

Could not merge changes ... with oldVersion = 5 and newVersion = 6

refresh object before updating and saving new changes

let myObject = viewContext.objectWithID(managedObjectId)
viewContext.refresh(myObject, mergeChanges: true)
myObject.property = newValue

https://stackoverflow.com/questions/39508077/coredata-merge-conflict-shows-managed-object-version-change-not-data

Observed Object

When passing an Core Data object into a child view, make sure the variable is marked as observable, otherwise it won't receive updates if modified.

struct ChildView: View {
    @ObservedObject var myModel: MyModel
    
    var body: some View {
        // ...
    }
}

Disable Core Data and CloudKit Debug Logs

-com.apple.CoreData.Logging.stderr 0
-com.apple.CoreData.CloudKitDebug 0

https://stackoverflow.com/a/59125651/1345618

Last Updated February 16, 2021