iosswiftuiresolverappstorage

SwiftUI @AppStorage not always persisting value


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:

Environment:

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


Solution

  • 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