Search code examples
swiftcore-dataswiftuiappstorage

Modifying CoreData data when @AppStorage is changed


I have a SwiftUI app that has some checkboxes to set some values to true or false using @AppStorage. I would like to remove modify some data from CoreData whenever those checkboxes are enabled or disabled.

How can I make my PersistenceController remove that data from CoreData depending on a certain checkbox being enabled/disabled?

Thanks in advance!


Solution

  • You can use onChange(of:perform:) to trigger a side effect as the result of a value changing. E.g.

     .onChange(of: playState) { [playState] newState in
           model.playStateDidChange(from: playState, to: newState)
     }