我是stackoverflow的新手,对SwiftUI编程也不是很有经验。我花了一整天的时间弄清楚如何备份我的Core Data存储并再次还原它。我想在本地而不是在云中保存sqlite文件。
我在这里找到了一篇很有帮助的文章:@Tom Harrington的https://www.atomicbird.com/blog/core-data-back-up-store/。他也在这里很活跃,希望他能看到我的帖子:)。这篇文章很棒!该代码可以很好地保存Core Data存储。但就我而言,加载它是行不通的。我在iPhone上使用XCode 11.5和iOS 13.5.1。似乎由于persistentStoreCoordinator.persistentStores为空而跳过了下面的整个部分。
for persistentStore in persistentStoreCoordinator.persistentStores {
guard let loadedStoreURL = persistentStore.url else {
continue
}
let backupStoreURL = backupURL.appendingPathComponent(loadedStoreURL.lastPathComponent)
guard FileManager.default.fileExists(atPath: backupStoreURL.path) else {
throw CopyPersistentStoreErrors.invalidSource("Missing backup store for \(backupStoreURL)")
}
do {
// Remove the existing persistent store first
try persistentStoreCoordinator.remove(persistentStore)
} catch {
print("Error removing store: \(error)")
throw CopyPersistentStoreErrors.copyStoreError("Could not remove persistent store before restore")
}
do {
// Clear out the existing persistent store so that we'll have a clean slate for restoring.
try persistentStoreCoordinator.destroyPersistentStore(at: loadedStoreURL, ofType: persistentStore.type, options: persistentStore.options)
// Add the backup store at its current location
let backupStore = try persistentStoreCoordinator.addPersistentStore(ofType: persistentStore.type, configurationName: persistentStore.configurationName, at: backupStoreURL, options: persistentStore.options)
// Migrate the backup store to the non-backup location. This leaves the backup copy in place in case it's needed in the future, but backupStore won't be useful anymore.
let restoredTemporaryStore = try persistentStoreCoordinator.migratePersistentStore(backupStore, to: loadedStoreURL, options: persistentStore.options, withType: persistentStore.type)
print("Restored temp store: \(restoredTemporaryStore)")
} catch {
throw CopyPersistentStoreErrors.copyStoreError("Could not restore: \(error.localizedDescription)")
}
}
有人知道出什么问题了吗?非常感谢。我也使用了搜索功能,但是找不到一些可以帮助我的提示...
问候, 美图