Home > Software design >  SwiftUI @AppStorage not always persisting value
SwiftUI @AppStorage not always persisting value

Time:05-27

I'm using @AppStorage with a String property. When changing the value of the property, the view automatically updates to reflect the change as expected. However, the majority of the time it hasn't persisted in UserDefaults. I'm feeling daft with the idea i've missed something here. Is anyone else seeing this?

Steps:

  • Launch app
  • Change value
  • Kill and re-launch app
  • Change value to something else
  • Kill and re-launch app

Environment:

  • Xcode 13.4 (13F17a)
  • iOS 15.5 - iPhone 13 Pro Simulator

Very simple example:

struct ContentView: View {
    @AppStorage("token") var token: String = ""

    var body: some View {
        Form {
            Section("Token") {
                Text(token)
            }

            Section("Debug") {
                Button("Update 01") {
                    token = "token-01"
                }

                Button("Update 02") {
                    token = "token-02"
                }
            }
        }
    }
}

Example gif

CodePudding user response:

This typical scenario can happen in development phase but not in production phase because there user doesn't have stop button like Xcode and UserDefault class write changes to disk before the app terminated by system.

So we know that user's default database is written to disk asynchronously, so may be the changes we made to default doesn't written to database when we stop the app from stop button on Xcode, you can try it own on your own by stopping app by swiping, your data will be stored when launch next time but when you stop from Xcode your data will not be saved

  • Related