在基于文档的SwiftUI应用程序中,我希望使用GRDB作为Sqlite包装器将每个文档持久化到单独的Sqlite文件中。在实现FileDocument协议的文档中加载Sqlite文件很简单,方法是为要加载的文件创建一个DatabaseQueue并使用其.backup(to:)方法复制到内存中的DatabaseQueue。如何在func fileWrapper(configuration: WriteConfiguration)方法中实现保存?似乎没有一种明显的方法来使用相同的.backup(to:)方法。
我在NSDocument的一个子类中找到了Andre Yonadam的一个example application,它以同样的方式实现了这一点:
override func write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
let destination = try DatabaseQueue(path: url.path)
do {
try memoryDBQueue.backup(to: destination)
} catch {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
override func read(from url: URL, ofType typeName: String) throws {
let source = try DatabaseQueue(path: url.path)
do {
try source.backup(to: memoryDBQueue)
} catch {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}发布于 2021-02-26 05:36:12
这可能不是最干净的解决方案,但我通过实现一个知道如何写入Sqlite文件的FileWrapper子类解决了这个问题:
class SqliteFileWrapper: FileWrapper {
var databaseQueue: DatabaseQueue
init (fromDatabaseQueue databaseQueue: DatabaseQueue) {
self.databaseQueue = databaseQueue
super.init(regularFileWithContents: "".data(using: .utf8)!)
}
required init?(coder inCoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func write(
to url: URL,
options: FileWrapper.WritingOptions = [],
originalContentsURL: URL?
) throws {
let destination = try DatabaseQueue(path: url.path)
do {
try databaseQueue.backup(to: destination)
} catch {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
}然后在我的FileDocument子类中,我创建了一个SqliteFileWrapper而不是FileWrapper:
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
SqliteFileWrapper(fromDatabaseQueue: memoryDBQueue)
}https://stackoverflow.com/questions/66359387
复制相似问题