How to retrieve string from UserDefaults in Swift?

橙三吉。 提交于 2019-12-08 12:07:09

问题


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


来源:https://stackoverflow.com/questions/28735244/how-to-retrieve-string-from-userdefaults-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!