UserDefaults

UserDefaults/NSUserDefaults

There are several different persistence mechanisms in iOS. The simplest to use is a persistent key-value store called UserDefaults. You might use UserDefaults for similar purposes as cookies in web development. They can store things like application settings, the current user, or a flag for whether a user has already seen a helpful hints popover.

Step 1: Saving Data

There are many data types that can be stored in UserDefaults including: array, bool, data, dictionary, float, integer, object, stringArray, string, double and url. Checkout the UserDefaults API Reference for more info.

To save a key to UserDefaults, do something like this:

//Access UserDefaultsletdefaults=UserDefaults.standard// Set a String value for some key.defaults.set("Hello World!",forKey:"myString")// Set an Integer value for some key.defaults.set(123,forKey:"myInt")// Set a Double value for some key.defaults.set(123.00,forKey:"myDouble")// Set a Bool value for some key.defaults.set(true,forKey:"myBool")// Set a Data value for some key.defaults.set(data,forKey:"currentUserData")// Force UserDefaults to save.defaults.synchronize()

//Access UserDefaults
NSUserDefaults*defaults=[NSUserDefaultsstandardUserDefaults];// Set a String value for some key.
[defaultssetObject:@"Hello World"forKey:@"myString"];// Set an Integer value for some key.
[defaultssetInteger:123forKey:@"myInt"];// Set a Double value for some key.
[defaultssetDouble:123.00forKey:@"myDouble"];// Set a Bool value for some key.
[defaultssetBool:YESforKey:@"myBool"];// Set a Data value for some key.
[defaultssetObject:dataforKey:@"currentUserData"];// Force UserDefaults to save.
[defaultssynchronize];

Note the synchronize call. UserDefaults automatically and periodically synchronizes, but to manually flush the keys and values to disk, call synchronize to guarantee that your updates are saved.

// Get a string value and provide a default string in the case the string is nil.letstringValue=defaults.string(forKey:"myString")??"my default string"// Get an Integer value.letintValue=defaults.integer(forKey:"myInt")// Get a Double value.letdoubleValue=defaults.double(forKey:"myDouble")// Get a Bool value.letboolValue=defaults.bool(forKey:"myBool")// Get a Data valueletdataValue=defaults.data(forKey:"myData")

// Get a string value and provide a default string in the case the string is nil.
NSString*stringValue=[defaultsstringForKey:@"myString"];// Get an Integer value.
NSIntegerintValue=[defaultsintegerForKey:@"myInt"];// Get a Double value.
doubledoubleValue=[defaultsdoubleForKey:@"myDouble"];// Get a Bool value.
BOOLboolValue=[defaultsboolForKey:@"myBool"];// Get a Data value
NSData*dataValue=[defaultsdataForKey:@"myData"];