FaddishWorm FaddishWorm -4 years ago 126
iOS Question

equivalent to shared preferences in ios

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?

Answer Source

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)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download