Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Mixing ReferenceFileDocument and @Observable

I have an app in which the data model is @Observable, and views see it through @Environment(dataModel.self) private var dataModel.

Since there are a large number of views, only some of which may need to be redrawn at a given time, I believe that @Observable is more efficient at run time than @Published and @ObservedObject

I’ve been trying to make the app document based. Although I started using SwiftData, it has trouble with Codable, and a long thread in the Developer forum suggests that SwiftData does not support the Undo manager - and in any event, simple JSON serialization is all that this app requires.

Unfortunately, ReferenceFileDocument inherits from ObservableObject, which seems to not play nice with @Observable.

I’d like to keep using @Observable, but haven’t been able to figure out how. When I deserialize a JSON ReferenceFileDocument, I can’t seem to connect it to an @Observable class instance and to let the various views and view models know where to find and update it.

I’d appreciate advice on how to implement document persistence in this app.

Also, the default behaviour of DoumentGroup provides a nice menu to, another things, rename a new file to something other than Untitled xx, but it doesn’t appear to work (there is an extensive thread on the Developer website discussing this issue). Is there a solution to this problem?

Thanks for any help you can offer.

Unfortunately, ReferenceFileDocument inherits from ObservableObject, which seems to not play nice with @Observable.

Is there any specific reason to make the document type a class, you could have a FileDocument-conforming struct and vent that to your View as a State or through a model object that conforms to @Observable.

The data model is only a class so it can adopt @Observable - otherwise it could be a Struct.

Even if it were a Struct, I don't know how to connect it to an @Observable class instance without losing the use of the Undo manager.

I don't know if @State shares the ability of @Observable to only update views that need to be redrawn following a data model change.

When I register Undos, I name them so that I can make the undo available via a menu selection that shows specifically what will be undone or redone. Hoping that a shake gesture will work seems much less desirable than giving the user explicit control over undo / redo - and in any event, I've read that the Undo manager doesn't actually work with SwiftData.

Mixing ReferenceFileDocument and @Observable
 
 
Q