Search code examples
swiftnsuserdefaults

userDefault value is not updated until the closing the app


I have a problem with userDefault, @Sh_Khan helped me on that but I couldn't fix the problem yet, so I ask it here with more details.

I created a userDefault to store a username

let user_name = UserDefaults.standard.string(forKey: "user_name")

I have a login page that when user taps on the login button, the username is saved in the UserDefaults.

let username = usernameInput?.text?.replacingOccurrences(of: " ", with: "")

   @IBAction func pressLoginBtn(_ sender: UIButton) {
   UserDefaults.standard.setValue(username, forKey: "user_name")
...
}

It saved and worked well, then in a profile page, which is a UIViewController, I have a logout button to send user back to the login page.

In this case, I assumed when user add a new username, the old value should replaced immediately with the new one, but It does, but the new value the UserDefaults still present the old value until I close the app and open it again, then it shows the new value

So, I tried to remove the value when the user click on the logout button:

  @IBAction func pressLogutBtn(_ sender: UIBarButtonItem) {
        UserDefaults.standard.removeObject(forKey: "user_name")
        print(user_name)
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "login")
        self.present(mainStoryboard,animated:true,completion:nil)
    }

The funny thing is, in the second line, I remove the value, but in the next line when I print it, it is still exist.

For the test, I add this print in the viewDidLoad in the profile page.

print(user_name)

Then, for example user add mrX username, so when the profile page is opened, it prints mrX. Then I press on logout and enter mrY username. Then when the profile page is opened, it still prints mrX, this process can be repeated many times and it still print mrX, until I close the app completely, then It prints mrY.

could anyone help on this? I really don't understand what is the problem here.


Solution

  • You can't read data instantly from userDefaults by the way you use.

    instead of this way:

    print(user_name)
    

    You should use:

    print(UserDefaults.standard.string(forKey: "user_name")!)