SwiftData .autosaveEnabled / rollback() trouble

Hello,

In my iOS/SwiftUI/SwiftData app, I want the user to be able to hit [Cancel] from editing in a detail screen and return to the previous screen without changes being saved.

I believed that setting autosaveEnabled to false and/or calling .rollback would prevent changes from being saved, unless/until I call .save() when the user clicks [Save], but this does not seem to be correct.

I set modelContext.autosaveEnabled = false and I call modelContext.rollback() when the user hits [Cancel], but any changes they made are not rolled back, but saved even if I don’t call save().

I have tried setting autosaveEnabled to false when I create the ModelContainer on a @MainActor function when the App starts, and in the detail/edit screen’s .onAppear(). I can see that .rollback is being called when the [Cancel] button is tapped. In all cases, any changes the user made before hitting [Cancel] are saved.

The Developer Documentation on autosaveEnabled includes this: “The default value is false. SwiftData automatically sets this property to true for the model container’s mainContext."

I am working on the mainContext, but it appears that setting autosaveEnabled to false has no effect no matter where in the code I set it.

If someone sees what I am doing wrong, I’d sure appreciate the input. If this description doesn’t explain the problem well enough, I’ll develop a minimal focused example.

SwiftData .autosaveEnabled / rollback() trouble
 
 
Q