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.

One option is to create and work with a local instance of ModelContext in your view and then call save() or rollback (or simply discard it) on that local instance. Once you call save the changes will be propagated to the main context.

One article about this can be found on https://www.hackingwithswift.com/quick-start/swiftdata/how-to-discard-changes-to-a-swiftdata-object or as part of this longer article, https://medium.com/@matgnt/the-art-of-swiftdata-in-2025-from-scattered-pieces-to-a-masterpiece-1fd0cefd8d87

SwiftData .autosaveEnabled / rollback() trouble
 
 
Q