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!
What you need to do is:
And later in the viewDidLoad:
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.
Special Considerations The returned string is immutable, even if the value you originally set was a mutable string.
You have to as follow: