Search code examples
iphonedefaultnsuserdefaultspreferencessynchronize

iPhone - Registered default prefs are not written to plist file


I have this (much much simplier) code on my app didFinishLaunchingWithOptions :

    NSDictionary *userDefaultsDefaults = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DefaultsPrefs" ofType:@"plist"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsDefaults];

    NSLog(@"--------------- NSUserDefaults dump : %@", [prefs dictionaryRepresentation]);
    BOOL a = [[NSUserDefaults standardUserDefaults] synchronize];

But nothing is written... I mean, no pref file is written. If I force [prefs setValue:someValue forKey:@"someKey"];, then the file is created with only this key/value

Why ? How may I set all default preferences then write them to disk ?

BOOL a is YES.
NSLog return the whole DefaultPrefs file content, plus some system values like :

AppleICUForce24HourTime = 1; 
AppleKeyboardsExpanded = 1;

Solution

  • How may I set all default preferences then write them to disk ?

    why? That nothing is written to disk is the whole point of defaults. They are default values, they are not set by the user, and they can change in a later version of your program.
    It's not wanted that they are saved in the preferences file. Once they are saved you can't distinguish between preferences that have been changed by the user and default values, and therefore you can't replace them with newer defaults.

    This behaves exactly like it should.

    If you want to write to the preferences file use [[NSUserDefaults standardUserDefaults] setObject:foo forKey:bar]

    I guess you can use a for loop to do it if you really want.

    for (NSString *key in userDefaultsDefaults) {
        [[NSUserDefaults standardUserDefaults] setObject:[userDefaultsDefaults objectForKey:key] forKey:key];
    }
    

    But you should reconsider if you really need to save those defaults. I can't think of a valid reason to do this.