Switching Core Data between local and CloudKit

I followed a tutorial on SwiftUI and macOS (and wow was it worth it, I understand more of what I was doing wrong before!). After the tutorial was done, I thought, okay, let's try adding CloudKit to it. Which was rather trivial to do, I was impressed. Then I thought, ok, let's try being able to have local or CloudKit, depending on runtime. But when I did that, the file was opened readonly, due to "Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey."

This seems to be something a lot of people have run into, but for some reason I haven't found any actual fixes. Anyone know?

Answered by kithrup in 709282022

Ok, this seemed to do it for me.

        persistentContainer = NSPersistentContainer(name: "DataModel")
        let description = persistentContainer.persistentStoreDescriptions.first
        description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                fatalError("\(error)")
            }
        }

I have a different class for CloudKit but I presume I could combine them more than I have.

I finally found this answer.

Accepted Answer

Ok, this seemed to do it for me.

        persistentContainer = NSPersistentContainer(name: "DataModel")
        let description = persistentContainer.persistentStoreDescriptions.first
        description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                fatalError("\(error)")
            }
        }

I have a different class for CloudKit but I presume I could combine them more than I have.

I finally found this answer.

Switching Core Data between local and CloudKit
 
 
Q