Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Created April 3, 2024 23:26
Show Gist options
  • Save mbrandonw/3be96d89ef9d7e7935867c16c8ee1273 to your computer and use it in GitHub Desktop.
Save mbrandonw/3be96d89ef9d7e7935867c16c8ee1273 to your computer and use it in GitHub Desktop.
/*
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)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment