iOS Equivalent For Android Shared Preferences
Use NSUserDefaults: - note that this is for small bits of data, such as the current level like you mentioned. Don't abuse this and use it as a large database, because it is loaded into memory every time you open your app, whether you need something from it or not (other parts of your app will also use this).
Objective-C:
Reading:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSString *currentLevelKey = @"currentlevel";
if ([preferences objectForKey:currentLevelKey] == nil)
{
// Doesn't exist.
}
else
{
// Get current level
const NSInteger currentLevel = [preferences integerForKey:currentLevelKey];
}
Writing:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSString *currentLevelKey = @"currentlevel";
const NSInteger currentLevel = ...;
[preferences setInteger:currentLevel forKey:currentLevelKey];
// Save to disk
const BOOL didSave = [preferences synchronize];
if (!didSave)
{
// Couldn't save (I've never seen this happen in real world testing)
}
.
Swift:
Reading:
let preferences = NSUserDefaults.standardUserDefaults()
let currentLevelKey = "currentLevel"
if preferences.objectForKey(currentLevelKey) == nil {
// Doesn't exist
} else {
let currentLevel = preferences.integerForKey(currentLevelKey)
}
Writing:
let preferences = NSUserDefaults.standardUserDefaults()
let currentLevelKey = "currentLevel"
let currentLevel = ...
preferences.setInteger(currentLevel, forKey: currentLevelKey)
// Save to disk
let didSave = preferences.synchronize()
if !didSave {
// Couldn't save (I've never seen this happen in real world testing)
}
Here is an update for Swift 3
Reading
let preferences = UserDefaults.standard
let currentLevelKey = "currentLevel"
if preferences.object(forKey: currentLevelKey) == nil {
// Doesn't exist
} else {
let currentLevel = preferences.integer(forKey: currentLevelKey)
}
Writing
let preferences = UserDefaults.standard
let currentLevel = ...
let currentLevelKey = "currentLevel"
preferences.set(currentLevel, forKey: currentLevelKey)
Update
From UserDefaults documentation
synchronize()
waits for any pending asynchronous updates to the defaults database and returns; this method is now unnecessary and shouldn't be used.
class Configuration {
static func value<T>(defaultValue: T, forKey key: String) -> T{
let preferences = UserDefaults.standard
return preferences.object(forKey: key) == nil ? defaultValue : preferences.object(forKey: key) as! T
}
static func value(value: Any, forKey key: String){
UserDefaults.standard.set(value, forKey: key)
}
}
Example
//set
Configuration.value(value: "my_value", forKey: "key_1")
//get
let myValue = Configuration.value(defaultValue: "default_value", forKey: "key_1")