So, let’s say we have an app that needs to remember a few simple things that the user puts in when they first load the app. Let’s say you want these things to be remembered by the app across application sessions. Even when the user closes the app or reboots their iOS device, you want these things to be remembered by the app.
One method we could use is NSUserDefaults. It is best when used for little bits of information like user preferences, but not for larger things like UIImages.
NSUserDefaults is read and written atomically. This means when you write something to it, the whole thing needs to be written again. And when you read one key from it, it reads the whole thing and presents just the key you requested. This is good for making sure the data is read and written correctly, but might effect performance if the amount of data in NSUserDefaults is large. It is cached after the initial app load, so subsequent reads should be quite fast, but the initial one could be slow.
NSUserDefaults is like a Property List or plist that saves stuff to the iOS defaults system. There are six data types it can store:
NSData NSString NSNumber UInt Int Float Double Bool NSDate NSArray NSDictionary
Initialising NSUserDefaults:
public let defaults = NSUserDefaults.standardUserDefaults()
Writing to NSUserDefaults:
defaults.setBool(value: Bool, forKey defaultName: String) defaults.setInteger(value: Int, forKey defaultName: String) defaults.setFloat(value: Float, forKey defaultName: String) defaults.setDouble(value: Double, forKey defaultName: String) defaults.setObject(value: AnyObject?, forKey defaultName: String) defaults.setURL(url: NSURL?, forKey defaultName: String) e.g. defaults.setBool(true, forKey: "myGroovyKey") defaults.setObject("myGroovyValue", forKey: "myGroovyKey")
The limit for how much data can be stored in NSUserDefaults is the maximum file size for iOS (logically), which is currently 4GB. But for large amounts of data storage, a good idea might be to use something else like core data.
Reading from NSUserDefaults:
defaults.boolForKey("myGroovyKey") defaults.integerForKey("myGroovyKey") defaults.floatForKey("myGroovyKey") defaults.doubleForKey("myGroovyKey") defaults.objectForKey("myGroovyKey") defaults.URLForKey("myGroovyKey") defaults.dataForKey("myGroovyKey") defaults.stringForKey("myGroovyKey") defaults.stringArrayForKey("myGroovyKey") defaults.arrayForKey("myGroovyKey") defaults.dictionaryForKey("myGroovyKey") e.g. if (defaults.boolForKey("myGroovyKey")) == true { do something awesome }
If you try to read a key and it does not exist it will return nil.