How to retrieve string from UserDefaults in Swift?

2019-06-09 11:58发布

问题:

I have a textField for the user to input their name.

 @IBAction func nameTextField(sender: AnyObject) {

    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject("\(nameTextField)", forKey: "userNameKey")


}

Then I recall the inputted name in ViewDidLoad with:

 NSUserDefaults.standardUserDefaults().stringForKey("userNameKey")

    nameLabel.text = "userNameKey"

What am I doing wrong? Result is simply "userNameKey" every time. I'm new to this, thanks!

回答1:

You just have to assign the result returned by nsuserdefaults method to your nameLabel.text. Besides that stringForKey returns an optional so I recommend using the nil coalescing operator to return an empty string instead of nil to prevent a crash if you try to load it before assigning any value to the key.

func string(forKey defaultName: String) -> String?

Return Value For string values, the string associated with the specified key. For number values, the string value of the number. Returns nil if the default does not exist or is not a string or number value.

Special Considerations The returned string is immutable, even if the value you originally set was a mutable string.

You have to as follow:

UserDefaults.standard.set("textToSave", forKey: "userNameKey")

nameLabel.text = UserDefaults.standard.string(forKey: "userNameKey")  ?? ""


回答2:

What you need to do is:

@IBAction func nameTextField(sender: AnyObject) {
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.set(yourTextField.text, forKey: "userNameKey")
}

And later in the viewDidLoad:

let defaults = NSUserDefaults.standardUserDefaults()

let yourValue = defaults.string(forKey: "userNameKey")

nameLabel.text = yourValue