Tuesday, May 10, 2016

Easiest Way to Persist Data

If your needs are simple, consider this option before moving on to other storage methods.

Saving

 
@IBOutlet weak var nameTextField: UITextField!

...

UserDefaults.standard.setValue(nameTextField.text, forKey: "name")
 

Retrieving

 
if let name = UserDefaults.standard.value(forKey: "name") as? String {
    nameTextField.text = name
}
 

Tips

Save some typing and create a variable to access the defaults:
  • let defaults = UserDefaults.standard
You can persist classes too but there is more work to it. May write another post for it.

(Swift 3.0)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...