Peeter Vedic Peeter Vedic - 3 months ago 11
Swift Question

How to recall name from NSUserDefaults swift?

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:


nameLabel.text = "userNameKey"

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


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 stringForKey(_ 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:

 NSUserDefaults.standardUserDefaults().setObject("textToSave", forKey: "userNameKey") 

 nameLabel.text = NSUserDefaults.standardUserDefaults().stringForKey("userNameKey")  ?? ""