How to use NSUserdefaults to save data

 

This tutorial has been updated for X code 7.3 & swift 2.2

NSUserdefaults is mostly used to save simple data type. For example app settings or high score in games. When you have lots of complex relations between data for example name, email, date of birth & more profile details then you save data with Core Data.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

new x code project

 

2. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

iPhone 4 inch

 

3. Add textfield & button to the main storyboard. Change button text to Save

add textfield & button

 

4. Select textfield and set its keyboard type to number

 

keyboard type to number pad

5. Connect textfield as outlet to swift file

textfield as outlet to swift file

 

6. Connect button as action to swift file

button as action to swift file

 

7 . Add following code in view did load

override func viewDidLoad() {
    super.viewDidLoad()
    if NSUserDefaults.standardUserDefaults().objectForKey("num") == nil {
        numText.text = "15"
    }
    else {
        let number = NSUserDefaults.standardUserDefaults().objectForKey("num") as! String
        numText.text =  number
    }
    // Do any additional setup after loading the view, typically from a nib.
}

This code checks if there is any value saved before & sets initial value for textfield.
8 . Add following code in save button action

@IBAction func saveButtonPressed(sender: UIButton) {
    if numText.text == nil {
        NSUserDefaults.standardUserDefaults().setObject("15", forKey: "num")
    }
    else {
        NSUserDefaults.standardUserDefaults().setObject(numText.text, forKey: "num")
    }
}

This code checks if textfield is empty & saves value in the snuserdefaults
Now build and run the app in iPhone 5s & test the app.

Screen Shot 2015-03-09 at 4.06.07 pm
Download X code file
Your challenge is to save UIColor using nsuserdefaults.

iOS Simulator Screen Shot 09-Mar-2015 4.10.49 pm
Download Challenge Solution

Total 3 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?