首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Sqlite和GRDB的SwiftUI FileDocument

使用Sqlite和GRDB的SwiftUI FileDocument
EN

Stack Overflow用户
提问于 2021-02-25 05:55:17
回答 1查看 204关注 0票数 1

在基于文档的SwiftUI应用程序中,我希望使用GRDB作为Sqlite包装器将每个文档持久化到单独的Sqlite文件中。在实现FileDocument协议的文档中加载Sqlite文件很简单,方法是为要加载的文件创建一个DatabaseQueue并使用其.backup(to:)方法复制到内存中的DatabaseQueue。如何在func fileWrapper(configuration: WriteConfiguration)方法中实现保存?似乎没有一种明显的方法来使用相同的.backup(to:)方法。

我在NSDocument的一个子类中找到了Andre Yonadam的一个example application,它以同样的方式实现了这一点:

代码语言:javascript
复制
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)
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-26 05:36:12

这可能不是最干净的解决方案,但我通过实现一个知道如何写入Sqlite文件的FileWrapper子类解决了这个问题:

代码语言:javascript
复制
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:

代码语言:javascript
复制
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
    SqliteFileWrapper(fromDatabaseQueue: memoryDBQueue)
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66359387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档