1

我有中间数据库,我在应用程序中预加载,然后我使用轻量级迁移来更新这个数据库,但是当我第一次调用 NSPersistentStoreCoordinator 时,我有一个错误“数据库磁盘映像格式错误”

对于预加载数据库,我在 AppDelegate didFinishLaunchingWithOptions 中使用以下代码

let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
if !FileManager.default.fileExists(atPath: url.path) {
    let sourceSqliteURLs = [Bundle.main.url(forResource: "SingleViewCoreData", withExtension: "sqlite")!, Bundle.main.url(forResource: "SingleViewCoreData", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "SingleViewCoreData", withExtension: "sqlite-shm")!]

    let destSqliteURLs = [self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite"),self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite-wal"),self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite-shm")]

    for index in stride(from:0, to: destSqliteURLs.count, by: 1) {
        do {
            try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index])
        } catch {
            print(error)
        }
    }
}

然后对于轻量级迁移,我使用新的核心数据模型 v 2 并将此代码添加到 persistentStoreCoordinator

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: mOptions)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

我做错了什么或如何解决这个问题?当我通过 Xcode 在设备上启动应用程序时,更新和安装始终有效,而当我使用 TestFlight 版本时,更新和安装无效......

4

0 回答 0