You can set and get NSUserPreferences from any view controller and the app delegate to they are a great way to pass data around the various parts of your iOS App.
Note: NSUserPreferences don’t cross the iOS/watchOS boundry. iOS and watchOS apps each have their own set of NSUserPreferences.
In the example below you have a class `Bool` property that you want to track between user sessions.
// inside some view controller class
var showAll = true
// inside viewDidLoad()
if let savedShowAll = NSUserDefaults.standardUserDefaults().objectForKey("savedShowAll") {
showAllStops = savedShowAllS as! Bool
}
// inside your action assocated a switch control
showAll = !showAll
NSUserDefaults.standardUserDefaults().setObject(showAll, forKey: "savedShowAll")
In the code above…
– The var showAll is the data model for a switch object value
– The string savedShowAll is the key for the stored value
– Use NSUserDefaults.standardUserDefaults().objectForKey() to access a stored value
– Use the if let idiom as the stored value might not exist
– Use NSUserDefaults.standardUserDefaults().setObject() to save the value
– Apparently setObject() never fails! 😀