Xcode8和Core Data自动轻量级迁移

时间:2016-10-01 17:10:34

标签: ios core-data xcode8 core-data-migration

我一直在尝试使用Xcode8为我的Core Data架构执行轻量级迁移,并遇到一些奇怪的问题。我第一次在更新后加载商店,并在选项字典中将NSMigratePersistentStoresAutomaticallyOptionNSInferMappingModelAutomaticallyOption标志设置为YES,我遇到了这个错误:

2016-10-01 09:59:17.307862 CJournal[1162:549816] loadLocalStoreIntoPSC using store = file:///private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/ContactsJournal.sqlite
2016-10-01 09:59:18.373568 CJournal[1162:549816] [error] error: Failed to delete support directory for store: /private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/.ContactsJournal.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3
2016-10-01 09:59:18.656164 CJournal[1162:549816] [error] error: CoreData: error: (migration) migration failed with error (null)
2016-10-01 09:59:18.664001 CJournal[1162:549816] [error] error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/ContactsJournal.sqlite options:{
    NSInferMappingModelAutomaticallyOption = 1;
    NSMigratePersistentStoresAutomaticallyOption = 1;
} ... returned error Error Domain=NSSQLiteErrorDomain Code=8 "(null)" UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/ContactsJournal.sqlite, Source database Path=/private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/.ContactsJournal.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3, reason=Failed to replace destination database} with userInfo dictionary {
    NSFilePath = "/private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/ContactsJournal.sqlite";
    "Source database Path" = "/private/var/mobile/Containers/Shared/AppGroup/04521C25-2FE6-4CFD-ACB5-70550B63499E/.ContactsJournal.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3";
    reason = "Failed to replace destination database";
}

在iOS10模拟器和iOS10设备上都会发生这种情况。奇怪的是第二次运行我运行应用程序并尝试迁移,它运行正常,没有任何错误!

这是我用来添加商店的代码:

NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:@YES, NSMigratePersistentStoresAutomaticallyOption, @YES, NSInferMappingModelAutomaticallyOption, nil];

NSPersistentStore *newStore = [self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:localStoreURL options:options error:&error];

我还尝试在"启动时传递的参数"中使用-com.apple.CoreData.MigrationDebug 1标志。但它并没有产生任何可能有用的输出。

知道可能出现什么问题,或者如果由于某些验证问题导致迁移失败,如何调试?

1 个答案:

答案 0 :(得分:0)

我发现了问题...在轻量级迁移之前,我正在对现有数据库进行备份,因此我创建了一个NSPersistentStoreCoordinator(与通常的堆栈分开)并向其添加了persistentStore没有任何轻量级迁移选项。这显然会锁定商店文件,即使在备份过程完成后,也会阻止主Core Data堆栈persistentStoreCoordinator上的迁移。解决方法是从备份persistentStoreCoordinator中删除persistentStore。这可以确保迁移正常,addPersistentStoreWithType此时不会抛出错误。