And*_*net 6 sqlite core-data ios nspersistentstore swift
我正在将我的 iOS 应用程序迁移到使用NSPersistentContainer. 默认情况下,此类将其持久存储文件定位在Library/Application Support目录中;以前我的商店文件存储在该Documents目录中。
我添加了一些代码来移动存储文件(如果在旧目录中找到它们):
func moveStoreFromLegacyLocationIfNecessary(toNewLocation newLocation: URL) {
// The old store location is in the Documents directory
let legacyStoreLocation = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("books.sqlite")
// Check whether the old store exists and the new one does not
if FileManager.default.fileExists(atPath: legacyStoreLocation.path) && !FileManager.default.fileExists(atPath: newLocation.path) {
print("Store located in Documents directory; migrating to Application Support directory")
let tempStoreCoordinator = NSPersistentStoreCoordinator()
try! tempStoreCoordinator.replacePersistentStore(at: newLocation, destinationOptions: nil, withPersistentStoreFrom: legacyStoreLocation, sourceOptions: nil, ofType: NSSQLiteStoreType)
// Delete the old store
try? tempStoreCoordinator.destroyPersistentStore(at: legacyStoreLocation, ofType: NSSQLiteStoreType, options: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
调用后destroyPersistentStore(at: url),存储文件仍然存在于磁盘上。这些会在某个时候自动清理吗?或者我应该删除它们?我还应该删除.sqlite-shm和.sqlite-wal文件吗?
状态的文档NSPersistentStoreCoordinator.destroyPersistentStore(at:type:options:):
删除所提供位置的特定类型的持久存储。
在与 WWDC 实验室的工程师交谈时,他们解释说,它实际上并没有删除所提供位置的数据库文件,正如文档似乎暗示的那样。它实际上只是截断而不是删除。如果您希望它们消失,您可以手动删除这些文件(如果您可以确保没有其他进程或不同的线程正在访问它们)。
这是我在我的应用程序中实现的:
try coordinator.replacePersistentStore(at: sharedStoreURL, destinationOptions: nil, withPersistentStoreFrom: defaultStoreURL, sourceOptions: nil, ofType: NSSQLiteStoreType)
try coordinator.destroyPersistentStore(at: defaultStoreURL, ofType: NSSQLiteStoreType, options: nil)
// destroyPersistentStore says it deletes the old store but it actually truncates so we'll manually delete the files
NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: defaultStoreURL.deletingLastPathComponent(), options: .forDeleting, error: nil, byAccessor: { url in
try? FileManager.default.removeItem(at: defaultStoreURL)
try? FileManager.default.removeItem(at: defaultStoreURL.deletingLastPathComponent().appendingPathComponent("\(container.name).sqlite-shm"))
try? FileManager.default.removeItem(at: defaultStoreURL.deletingLastPathComponent().appendingPathComponent("\(container.name).sqlite-wal"))
try? FileManager.default.removeItem(at: defaultStoreURL.deletingLastPathComponent().appendingPathComponent("ckAssetFiles"))
})
Run Code Online (Sandbox Code Playgroud)
我提交了 FB10181832 请求更新文档以更好地解释其行为。
| 归档时间: |
|
| 查看次数: |
592 次 |
| 最近记录: |