1

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

1
  • 1
    The question is about "kill app" - how do you do that? UserDefaults, which is used internally by AppStorage, does not synchronise immediately on entered changes, so you might just lost data by force-quit. In short - read documentation about UserDefaults behavior. Commented May 27, 2022 at 5:37

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

3 Comments

You might be interested to know since iOS 8 a daemon now reads and writes the defaults database not the app: iphonedev.wiki/index.php/Preferences
@malhal: So you want to say Umair Khan's answer is incorrect?
@soundflix would need to test, the save behaviour of defaults changes all the time!
0

The answers above are correct, but I don't see the solution anywhere so I'll add it here:

Just always background your app before you terminate it from Xcode

PS: the answer is not, nor has never been, to call .synchronize on user defaults

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.