Question

I have an issue I've been struggling with for the last few days. I have a settings bundle, root.plist, which holds some user preferences. In it are three multivalue menu items. One returns a boolean, the other two return numbers.

When I call [[NSUserDefaults standardUserDefaults] dictionaryRepresentation] and examine it in the console, only the first item in the property list shows up with its value. The other two are conspicuously absent. As a result, when I try to retrieve those values, I get zero.

What's weirder is that the settings bundle looks correct in the Settings app on the iPhone. The only thing not working is that the values are not getting passed. As far as my app is concerned, the other two multivalue menu items don't even exist.

Any suggestions are greatly appreciated.

Was it helpful?

Solution

I've used this block of code, multiple times, in applicationDidFinishLaunchingWithOptions to initialize my user defaults.

    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"somePropertyYouExpect"])  {

    NSString  *mainBundlePath = [[NSBundle mainBundle] bundlePath];
    NSString  *settingsPropertyListPath = [mainBundlePath
                                           stringByAppendingPathComponent:@"Settings.bundle/Root.plist"];

    NSDictionary *settingsPropertyList = [NSDictionary 
                                          dictionaryWithContentsOfFile:settingsPropertyListPath];

    NSMutableArray      *preferenceArray = [settingsPropertyList objectForKey:@"PreferenceSpecifiers"];
    NSMutableDictionary *registerableDictionary = [NSMutableDictionary dictionary];

    for (int i = 0; i < [preferenceArray count]; i++)  { 
        NSString  *key = [[preferenceArray objectAtIndex:i] objectForKey:@"Key"];

        if (key)  {
            id  value = [[preferenceArray objectAtIndex:i] objectForKey:@"DefaultValue"];
            [registerableDictionary setObject:value forKey:key];
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:registerableDictionary]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

OTHER TIPS

Make sure you are using - (void)registerDefaults:(NSDictionary *)dictionary on NSUserDefaults. Otherwise your defaults will not get pulled from the Bundle.

You have to do this early in your application, before you try to retrieve any of the default values.

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top