1

I am trying to use a @Stateobject in my document as source of truth for the dataModel behind the document. However, it seems I am doing something wrong as I appear to get different instances for the document and the content view, which is in line with the warnings I am receiving: Accessing StateObject's object without being installed on a View. This will create a new instance each time.

Can anybody help? I am pretty sure this has a very simple fix...

Here is the code:

Observed Object:

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

App:

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

Document (partial):

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

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

ContentView:

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

2
  • 1
    As the warning alludes to, @StateObject is for use inside a View -- you're trying to own it inside a FileDocument. What happens if you just remove the property wrapper? Commented Mar 9, 2022 at 19:29
  • I originally designed it to have the data object directly as a variable of the document, however, I get problems if I re-shape the data in response to user input as the View will hit it and cause out-of-bounds errors etc. I thought putting it into a observable object, I can prevent those errors (object will change notifications) Commented Mar 9, 2022 at 20:17

1 Answer 1

1

@StateObject is just for Views, try 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.