0

I'm trying to take the NSUserDefaults.standardUserDefaults route of storing data into an iOS device. I know this is not the best method, but I'm just trying it out for practice (I know the data is erased when you restart the simulator or delete the app from the device). My main goal is to get the data stored within the iOS device and then pull it back up displayed on another view controller after submission. I thought that I could maybe display it as a Label, but I'm still having trouble recalling that information when stored and pulling in up in a different view controller. Sorry if this is not enough information, I can supply more if needed in a bit.

I'm typing the value into a textfield

@IBOutlet weak var userNameTextField: UITextField!

And then I submit the data with a button

@IBAction func submitButton(sender: AnyObject) {
    let userName = userNameTextField.text;
    NSUserDefaults.standardUserDefaults().setObject(userName, forKey: "userName")
    NSUserDefaults.standardUserDefaults().synchronize()
}

Is synchronize necessary or is that only needed with multiple text fields being submitted?

Again, I just want to take the submitted data and be able to see/view/display it on another view controller page.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    what is the issue you are facing ? – Teja Nandamuri Nov 28 '15 at 14:49
  • The synchronize is a good idea because, without it, information is written to persistent storage "periodically". If your app is terminated without a synchronize, your data may not be available on next launch. – Phillip Mills Nov 28 '15 at 14:53
  • There is not an issue storing the data. I just want to pull the data stored. For example I want to the see whatever was inputted as the constant userName and display it on another view controller when they click submit, displaying the name. And thanks for the synchronize advice. – user3795450 Nov 28 '15 at 14:56
  • Okay I will try to make it so I can print it as a label, thank you for the help – user3795450 Nov 28 '15 at 15:00
  • 1
    Your question states that you are having trouble recalling the information from `NSUserDefaults`. Update your question with what you have tried and explain what issues you are having. – rmaddy Nov 28 '15 at 15:35

1 Answers1

0

To save then retrieve the data, you want to do something like this:

 let textToSave = userNameTextField.text;
 let defaults = NSUserDefaults.standardUserDefaults()
 defaults.setObject(textToSave, forKey: "myKey")

Then to retrieve it and set a labels text as that (for example) do this:

let defaults = NSUserDefaults.standardUserDefaults()
myLabel.text = defaults.stringForKey("myKey")

the stringForKey method returns whatever you saved in that key previously

arc4randall
  • 3,275
  • 3
  • 27
  • 40