Dima Deplov
Dima Deplov

Reputation: 3718

Setting default settings in NSUserDefaults. What I do wrong?

I made custom plist with default settings according to this Apple documentation page and with help of this answer on question at SO.

Here is my app delegate code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@"defaultSettings" ofType:@"plist"];
   NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
   [[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];

   // Override point for customization after application launch.
   return YES;
}

I also made plist with name defaultSettings .plist and store here my default settings.

here it's structure:

<dict>
    <key>Sound</key>
    <true/>
    <key>Music</key>
    <true/>
    <key>Difficulty</key>
    <integer>0</integer>
</dict>

In my settings VC, I set from plist my outlets and store to plist when values changes.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    self.soundSwitcher.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Sound"];

    ....  

    self.difficultySelector.selectedSegmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"Difficulty"];
}

It seems alright but outlets doesn't set to my defaults that set in property list itself. I can't also change this value by IBAction method

- (IBAction)switchSound:(UISwitch *)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:@"Sound"];
}

What I do wrong?

Edit: I want to mention, that if I close settings View Controller and then open it again, settings saves as I left it. (So, in fact all work). But If I relaunch my app, all settings is unset.

Upvotes: 1

Views: 389

Answers (1)

Fran Martin
Fran Martin

Reputation: 2369

You forgot to write this after to change something in NSUserDefaults

[defaults synchronize];

Upvotes: 2

Related Questions