CoreData with CloudKit报错513解决方案

553 阅读1分钟

业务场景:

之前用CoreData做数据管理时用的NSPersistentContainer,现在想要做CloudKit数据备份需要用到NSPersistentCloudKitContainer,但两者做衔接时遇到了问题:操作数据总发生崩溃和数据无法保存

错误特征:

Thread 1: Fatal error: 不能保存:Error Domain=NSCocoaErrorDomain Code=513 "未能存储该文件,因为你没有权限。" UserInfo={NSPersistentStoreOptions={ NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; }, reason=File is in Read Only mode due to Persistent History being detected but NSPersistentHistoryTrackingKey was not included., storeURL=

解决方案:

一旦启用了iCloud同步的NSPersistentCloudKitContainer,想再切换到NSPersistentContainer做数据操作,必须开启NSPersistentHistoryTrackingKey

struct LocalPersistentContainer {

    static** var shared: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "NoteData")

        // 重点在于这两句
        let description = container.persistentStoreDescriptions.first
        description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
        // 无需重新赋值给container即可生效
        
        

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

            if let error = error as NSError? {

                print("Unresolved error \(error), \(error.userInfo)")

            }

        })

        **return** container

    }()

    

}