SwiftData and discarding unsaved changes idea???

Someone smarter than me please tell me if this will work... I want to have an edit screen for a SwiftData class. Auto Save is on, but I want to be able to revert changes. I have read all about sending a copy in, sending an ID and creating a new context without autosave, etc.

What about simply creating a second set of ephemeral values in the actual original model. initialize them with the actual fields. Edit them and if you save changes, migrate that back to the permanent fields before returning.

Don't have to manage a list of @State variables corresponding to every model field, and don't have to worry about a second model context.

Anyone have any idea of the memory / performance implications of doing it this way, and if it is even possible? Does this just make a not quite simple situation even more complicated? Haven't tried yet, just got inspiration from reading some medium content on attributes on my lunch break, and wondering if I am just silly for considering it.

Answered by joadan in 849618022

I would recommend using a struct instead that mirrors the properties in the model, no more work really than working with duplicate properties and probably much easier to handle state changes etc.

Accepted Answer

I would recommend using a struct instead that mirrors the properties in the model, no more work really than working with duplicate properties and probably much easier to handle state changes etc.

After many tries and different options, the best seems to be to create a private state temp variable of the same type as your @Bindable parameter. Then use .task{} to assign each of the values of the parameter to the temp variable. Edit away on the temp variable - and then when you are done, if you discard changes, simply navigate back. If you save changes, then copy temp variable back to the parameter before navigating back. So just like joadan said.

SwiftData and discarding unsaved changes idea???
 
 
Q