Swift: Persisting and loading data from NSUserDefaults

To save data to NSUserDefaults:

@IBAction func saveDataClicked(sender: AnyObject) {
 
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

defaults.setObject(self.firstNameTextField.text, forKey: "firstName")
defaults.setObject(self.lastNameTextField.text, forKey: "lastName")
defaults.setObject(self.emailTextField.text, forKey: "email")
defaults.setObject(self.phoneNumberTextField.text, forKey: "phoneNumber")

defaults.synchronize()
 
 }

To load data from NSUserDefaults:

@IBAction func loadDataClicked(sender: AnyObject) {
 
 var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

 if let firstNameIsNotNill = defaults.objectForKey("firstName") as? String {
 self.firstNameTextField.text = defaults.objectForKey("firstName") as String
 }
 
if let lastNameIsNotNill = defaults.objectForKey("lastName") as? String {
 self.lastNameTextField.text = defaults.objectForKey("lastName") as String
 }
 
if let emailIsNotNill = defaults.objectForKey("email") as? String {
 self.emailTextField.text = defaults.objectForKey("email") as String
 }
 
if let phoneNumberIsNotNill = defaults.objectForKey("phoneNumber") as? String {
 self.phoneNumberTextField.text = defaults.objectForKey("phoneNumber") as String
 }

 }

One Response to Swift: Persisting and loading data from NSUserDefaults

Leave a Reply