Dan
Dan

Reputation: 2344

Where should I store NSUserDefaults so I can update them?

I understand there are a few questions on where to store userDefaults so they're available to everyone. Currently I have mine in the AppDelegate and it's working. However I now want to update a default setting per a users preference.

However, when the user exits the app and starts it again it simply creates the defaults from scratch again.

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    NSUserDefaults *sharedPref = [NSUserDefaults standardUserDefaults];
    [sharedPref setObject:@"Washington, DC" forKey:@"defaultLocation"];
    //  

    return YES;
}

Obviously this gets set each time the app opens, rendering the users choice obsolete.

How can you set a default and then let a user change it without it then being overwritten when the app starts?

Thanks

Upvotes: 0

Views: 236

Answers (3)

Sunil Zalavadiya
Sunil Zalavadiya

Reputation: 1993

The following code runs a check for whether or not the app has been launched. It aims to replace -registerDefaults:.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"setupApp"])
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setBool:YES forKey:@"setupApp"];
            [defaults setObject:@"Washington, DC" forKey:@"defaultLocation"];

            [defaults synchronize];
        }
    return YES;
}

Upvotes: 1

Marcelo
Marcelo

Reputation: 9944

You should use registerDefaults: for that

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 // ...
    [NSUserDefaults standardUserDefaults] registerDefaults:@{@"defaultLocation" : @"Washington, DC"}];
// ...
    return YES;
}

Upvotes: 4

Mike D
Mike D

Reputation: 4946

NSUserDefaults is a singleton available to the entire application. You can call it anytime by:

[NSUserDefaults standardUserDefaults]

Users can not interact directly with it, you will have to collect the data and then store it. To set a value:

[[NSUserDefaults standardUserDefaults] setObject:@"Some Value" forKey:@"MyKey"];
[[NSUserDefaults standardUserDefaults] synchronize];  // to save

The user defaults will persist between application launches.

You have to be careful about setting objects, only property list types can be set in the user defaults.

Ref

Upvotes: 0

Related Questions