SwiftUI 中“DocumentGroups”的“FileDocument”和“ReferenceFileDocument”有什么区别?

Jos*_*son 12 swiftui documentgroup

我正在尝试在我的应用程序中设置 a DocumentGroup,但还没有ReferenceFileDocument可用的示例。我知道 aFileDocument是什么,但ReferenceFileDocuments 有什么不同。

文档中它说的是:

与 ReferenceFileDocument 的一致性预计是线程安全的,并且反序列化和序列化将在后台线程上完成。

ste*_*vex 11

名称中有一个暗示: ReferenceFileDocument是一个引用类型(即类)的文档。FileDocument 用于基于结构的文档。

这会影响文档的保存方式,因为 SwiftUI 可以只复制引用类型并保存它,而不必担心您在保存过程中修改它,因为它是值类型或值类型树。

对于ReferenceFileDocument,似乎也没有一个明确的方法让 SwiftUI 知道何时保存,所以这取决于你告诉它。没有直接的“文档已脏,立即保存”方法,因此您通知 SwiftUI 您已完成需要保存的操作的方式是通过撤消管理器。

您还需要提供一种snapshot方法来返回可以安全保存的文档副本。

final class QuizDocument: ReferenceFileDocument, ObservableObject {
    
    @Published var quiz: QuizTemplate

    init(quiz: QuizTemplate) {
        self.quiz = quiz
    }

    static var readableContentTypes: [UTType] { [.exampleText] }

    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
              let quiz = try? JSONDecoder().decode(QuizTemplate.self, from: data)
        else {
            throw CocoaError(.fileReadCorruptFile)
        }

        self.quiz = quiz
    }

    // Produce a snapshot suitable for saving. Copy any nested references so they don't
    // change while the save is in progress.
    func snapshot(contentType: UTType) throws -> QuizTemplate {
        return self.quiz
    }

    // Save the snapshot
    func fileWrapper(snapshot: QuizTemplate, configuration: WriteConfiguration) throws -> FileWrapper {
        let data = try JSONEncoder().encode(quiz)
        return .init(regularFileWithContents: data)
    }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*son 7

ReferenceFileDocument是一种会在后台自动保存的文档类型。它通过 通知更改UndoManager,因此为了使用它,您还必须使您的文档可撤消。

我在文档中看到的唯一提及是here

是一个工作示例。