iOS Equivalent For Android Shared Preferences

FaddishWorm picture FaddishWorm · Oct 6, 2013 · Viewed 62.7k times · Source

I am porting an Android app to iOS, one thing I used was the Shared Preferences in Android to save each time a level was complete.

That way when the user gets back into the app, they can see they are up to level 3 or whatever.

Is there a similar mechanism in iOS? or do I have to manually write out to an application specific file?

If so, how do I write out to files only visible to my application?

Thanks.

Answer

SomeGuy picture SomeGuy · Oct 6, 2013

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)
}