Created
April 3, 2024 23:26
-
-
Save mbrandonw/3be96d89ef9d7e7935867c16c8ee1273 to your computer and use it in GitHub Desktop.
Revisions
-
mbrandonw created this gist
Apr 3, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ /* The @AppStorage property wrapper does not fully work unless installed directly in a view. In particular, it does not work when used in an observable object. Paste the following into a fresh project, run it in the simulator, and notice that tapping the "Toggle model.isOn" button causes the view to update propertly, but tapping the "Toggle UserDefaults directly" button does not. This means that writing directly to user defaults does cause @AppStorage to update, _unless_ @AppStorage is used in the view. */ import SwiftUI @main struct MainApp: App { var body: some Scene { WindowGroup { FeatureView() } } } class FeatureModel: ObservableObject { @AppStorage("isOn") var isOn = false } struct FeatureView: View { @ObservedObject var model = FeatureModel() var body: some View { Form { Section { Text("model.isOn: \(model.isOn.description)") } Section { Button("Toggle model.isOn") { model.isOn.toggle() } Button("Toggle UserDefaults directly") { print("model.isOn before", model.isOn) UserDefaults.standard.setValue( !UserDefaults.standard.bool(forKey: "isOn"), forKey: "isOn" ) print("model.isOn after", model.isOn) } } } } }