Search code examples
iosswiftasynchronousuiviewcontrolleruserdefaults

set value in UserDefaults synchronously


I am trying to save boolean in UserDefault in swift. so when I set value in userDefault, my very next instruction is to switch to view controller and close the current view controller.

so, what is happening now is, sometimes userDefault saves the value in DB, and sometimes it doesn't. I read documentation from Apple https://developer.apple.com/documentation/foundation/userdefaults and found that

At runtime, you use UserDefaults objects to read the defaults that your app uses from a user’s defaults database. UserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.

so, I guess because in the very next line I open a new controller and close the current one so due to which there is inconsistency.

here is my code

func setWalkthroughShown(completionHandler: @escaping ()->()) {
        UserDefaults.standard.set(true, forKey: isWalkthroughCompleted)
        UserDefaults.standard.synchronize()
        completionHandler()
    }

I even called UserDefaults.standard.synchronize() so that operation may become synchronous. even though in the documentation it is clearly written not to use this function. can someone please guide me where I am wrong? how can I save across all places before closing the current process?

this is the function by which I am retrieving value

func isWalkthroughShown() -> Bool {
        return UserDefaults.standard.bool(forKey: isWalkthroughCompleted)
    }

here isWalkthroughCompleted is a string and you can see I am using same string for saving and retrieving value


Solution

  • Actually, there was no syntax error in coding.

    I was actually testing it in the wrong way. after submitting for the request of saving data in userdefaults, I was recompiling immediately and as value stores asynchronously so sometimes due to killing of the process I was getting this issue. thanks to @matt. for detail iOS UserDefaults falls behind saved content