Ошибка переноса данных ядра NSPersistentCloudKitContainer - попытка записи базы данных только для чтения - PullRequest
0 голосов
/ 17 марта 2020

Я использую swift 4.2 и Core Data.

Я использую NSPersistentCloudKitContainer для использования cloudkit.

И я готовлю некоторую миграцию с этим сообщением в блоге.

https://williamboles.me/progressive-core-data-migration/

При переносе версии 1 в версию 2 с помощью стандартной миграции с помощью mappingmodel возникает ошибка выброса migrateStore.

ошибка: Ошибка домена = NSCocoaErrorDomain Code = 134110 " Произошла ошибка во время постоянной миграции хранилища. " UserInfo = {sourceURL = file: ///var/mobile/Containers/Data/Application/C29C3599-C6C0-482C-B300-8E95E8CF6EA9/Library/Application%20Support/Model.sqlite, причина = невозможно перенести хранилище в место: ошибка во время SQL выполнение: попытка записи базы данных только для чтения, destinationURL = файл: /// var / mobile / Containers / Data / Application / C29C3599-C6C0-482 C -B300-8E95E8CF6EA9 / Library / Application% 20Support / Model.sqlite, NSUnderlyingError = 0x28060fd20 {Error Domain = NSCocoaErrorDomain Code = 134110 «Произошла ошибка во время постоянной миграции хранилища». UserInfo = {NSSQLiteErrorDomain = 8, NSFilePath = / private / var / mobile / Containers / Data / Application / C29C3599-C6C0-482 C -B300-8E95E8CF6EA9 / tmp / 943B1603-E25F-4148-8BB8-16C51D5NBB6-16B6NeBD во время SQL выполнение: попытка записи базы данных только для чтения, причина = ошибка во время SQL выполнение: попытка записи базы данных только для чтения}}}: файл / Users / yeonsukchoi / Desktop / git / DDiary / DDiary / Model / Migration. swift, строка 109

enter image description here

Мой код CoreDataStack.

lazy var storeContainer: NSPersistentContainer = {
    let container: NSPersistentContainer!

    let isICloudOn = UserDefaults.standard.value(forKey: "isICloudOn") as? Bool ?? false

    if isICloudOn {  
        container = NSPersistentCloudKitContainer(name: self.modelName)
    } else { 
        container = NSPersistentContainer(name: self.modelName)  
    }

    // Enable history tracking and remote notifications
    guard let description = container.persistentStoreDescriptions.first else {
        fatalError("###\(#function): Failed to retrieve a persistent store description.")
    }
    description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
    description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
    description.shouldInferMappingModelAutomatically = false //inferred mapping will be handled else where
    description.shouldMigrateStoreAutomatically = false
    description.type = NSSQLiteStoreType
    description.isReadOnly = false

    // Pin the viewContext to the current generation token and set it to keep itself up to date with local changes.
    container.viewContext.automaticallyMergesChangesFromParent = true
    do {
        try container.viewContext.setQueryGenerationFrom(.current)
    } catch {
        fatalError("###\(#function): Failed to pin viewContext to the current generation:\(error)")
    }

    // Observe Core Data remote change notifications.
    NotificationCenter.default.addObserver(
        self, selector: #selector(type(of: self).storeRemoteChange(_:)),
        name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)

    return container
}()

И код миграции почти совпадает с верхним post.

// MARK: - Migration

func migrateStore(at storeURL: URL, toVersion version: CoreDataMigrationVersion) {
    forceWALCheckpointingForStore(at: storeURL)

    var currentURL = storeURL
    let migrationSteps = self.migrationStepsForStore(at: storeURL, toVersion: version)

    for migrationStep in migrationSteps {
        let manager = NSMigrationManager(sourceModel: migrationStep.sourceModel, destinationModel: migrationStep.destinationModel)
        let destinationURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)

        do {
            try manager.migrateStore(from: currentURL, sourceType: NSSQLiteStoreType, options: nil, with: migrationStep.mappingModel, toDestinationURL: destinationURL, destinationType: NSSQLiteStoreType, destinationOptions: nil)
        } catch let error {
            fatalError("failed attempting to migrate from \(migrationStep.sourceModel) to \(migrationStep.destinationModel), error: \(error)")
        }

        if currentURL != storeURL {
            //Destroy intermediate step's store
            NSPersistentStoreCoordinator.destroyStore(at: currentURL)
        }

        currentURL = destinationURL
    }

    NSPersistentStoreCoordinator.replaceStore(at: storeURL, withStoreAt: currentURL)

    if (currentURL != storeURL) {
        NSPersistentStoreCoordinator.destroyStore(at: currentURL)
    }
}

Есть ли что-то не так?

Или есть ли рекомендации по миграции nspersistentcloudkitcontainer?

Спасибо.

...