How to retrieve string from UserDefaults in Swift?

2019-06-09 11:50发布

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!

2条回答
相关推荐>>
2楼-- · 2019-06-09 12:09

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
查看更多
一纸荒年 Trace。
3楼-- · 2019-06-09 12:24

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")  ?? ""
查看更多
登录 后发表回答