In this post we will see how we can use iOS NSUserDefaults to save data or application settings. iOS NSUserDefaults is often used to store the application settings. Suppose you need to store some small data in the app like username, gender or any kind of thing that usually doesn’t need a database. In this case you can use iOS NSUserDefaults to save these settings. So lets begin.
What you can store in iOS NSUserDefaults
Though you cannot store everything in NSUserDefaults. These are some common things that you can store using iOS NSUserDefaults.
- NSData
- NSString
- NSNumber
- NSDate
- NSArray
- NSDictionary
If you go in depth then you know that you can store almost anything 😛 . Though still there is some limitation. But lets know how we can write data to iOS NSUserDefaults.
Writing to iOS NSUserDefaults
Writing to NSUserDefaults is very easy. See the following code snippet.
let defaultValues = NSUserDefaults.standardUserDefaults() defaultValues.setObject("Simplified iOS", forKey: "nameKey")
In the first line we are creating a reference in defaultValues, now this defaultValues can access the NSUserDefaults. Then in the second line we are putting a simple String to the defaultValues. The data are stored in name value pair and the name is passed in the second parameter after forKey: .
These are some more methods to write data in NSUserDefaults
func setBool(value: Bool, forKey defaultName: String) func setInteger(value: Int, forKey defaultName: String) func setFloat(value: Float, forKey defaultName: String) func setDouble(value: Double, forKey defaultName: String) func setObject(value: AnyObject?, forKey defaultName: String) func setURL(url: NSURL?, forKey defaultName: String)
Reading from iOS NSUserDefaults
Reading from NSUserDefaults is also very easy. See the following code snippet.
let defaultValues = NSUserDefaults.standardUserDefaults() if let name = defaultValues.stringForKey("nameKey") { //use the name variable here }
In the above code again we are creating a reference to NSUserDefaults. And to get the saved name we are using the function stringForKey.
These are some more methods to read data from NSUserDefaults
func boolForKey(defaultName: String) -> Bool func integerForKey(defaultName: String) -> Int func floatForKey(defaultName: String) -> Float func doubleForKey(defaultName: String) -> Double func objectForKey(defaultName: String) -> AnyObject? func URLForKey(defaultName: String) -> NSURL? func dataForKey(defaultName: String) -> NSData? func stringForKey(defaultName: String) -> String? func stringArrayForKey(defaultName: String) -> [String]? func arrayForKey(defaultName: String) -> [AnyObject]? func dictionaryForKey(defaultName: String) -> [String : AnyObject]?
Now lets see a practical example of reading and writing data using iOS NSUserDefaults.
iOS NSUserDefaults Example Application
Creating a New Xcode Project
So first we will create a new Xcode Project. The process is same as we did in the previous tutorials.
- Create a Single View iOS App.
Adding Views to Storyboard
- Now click on Main.storyboard and from the right drag Two Button, One Text Field and One Label on the storyboard, as show in the below image. We will use the Label to display the saved name.
- Now we will connect these views to our ViewController.swift file. The process is very simple and we discussed connecting views to swift file in previous tutorials. You can check the previous Xcode Button Tutorial if you don’t know about the connection process.
Writing Data to iOS NSUserDefaults
- After connecting the views to swift file we can use the above learnt code to save name in NSUserDefaults. See the following code.
// // ViewController.swift // NSUserDefaultsExample // // Created by Belal Khan on 10/08/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textFieldName: UITextField! @IBAction func buttonClick(sender: UIButton) { //getting name from text field let name = textFieldName.text //storing to nsuserdefaults let defaultValues = NSUserDefaults.standardUserDefaults() defaultValues.setObject(name, forKey: "nameKey") //displaying a success alert let alertController = UIAlertController(title: "Simplified iOS", message: "Name saved successfully", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
- Now try running your application in simulator.
- So the saving works fine. Lets try reading the saved values from iOS NSUserDefaults.
Reading Data from iOS NSUserDefaults
- To read values connect the save button and label to your swift code and write the following code.
// // ViewController.swift // NSUserDefaultsExample // // Created by Belal Khan on 10/08/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var labelName: UILabel! @IBOutlet weak var textFieldName: UITextField! @IBAction func buttonClick(sender: UIButton) { let name = textFieldName.text let defaultValues = NSUserDefaults.standardUserDefaults() defaultValues.setObject(name, forKey: "nameKey") let alertController = UIAlertController(title: "Simplified iOS", message: "Name saved successfully", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) } @IBAction func buttonGet(sender: AnyObject) { //getting the reference let defaultValues = NSUserDefaults.standardUserDefaults() //getting the name saved if let name = defaultValues.stringForKey("nameKey") { //displaying the name labelName.text = name } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
- Now again run your app in simulator.
- So its working absolutely fine. If you are having any trouble you can download my source code from the below link.
[sociallocker]  iOS NSUserDefaults Swift Example  [/sociallocker]
So thats all for this iOS NSUserDefaults Swift Example friends. Feel free to leave your comments if having any confusions or doubts regarding this iOS NSUserDefaults Swift Example. Thank You 🙂
Leave a Reply