在基于文档的 SwiftUI 应用程序中使用@StateObject:获取实例而不是引用

Use of @StateObject in Document-based SwiftUI application: getting instances instead of references

我正在尝试在我的文档中使用@Stateobject 作为文档背后的数据模型的真实来源。但是,似乎我做错了什么,因为我似乎得到了文档和内容视图的不同实例,这与我收到的警告一致:Accessing StateObject's object without being installed on a View. This will create a new instance each time.

有人可以帮忙吗?我很确定这有一个非常简单的修复...

代码如下:

观察对象:

class TestObject:ObservableObject{
    @Published var text: String
    init(){
        text = "initString"
    }
}

应用程序:

@main
struct FileOpen5App: App {
    var body: some Scene {
        DocumentGroup(newDocument: FileOpen5Document()) { file in
            ContentView(document: file.$document, obj: file.document.docObject) /// instance warning
        }
    }
}

文档(部分):

struct FileOpen5Document: FileDocument {
    //var text: String
    @StateObject var docObject = TestObject()

    init() {
        docObject.text = "DocText" /// instance warning
    }
...

内容视图:

struct ContentView: View {
    @Binding var document: FileOpen5Document
    @ObservedObject var obj: TestObject
    
    var body: some View {
        Text(obj.text)
    }
}
'''

@StateObject 仅用于视图,请尝试 ReferenceFileDocument but before you resort to using classes I highly recommend figuring out if you can stick to structs because Swift and SwiftUI work best with value types. See https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes