views:

75

answers:

1

My iPhone app has the following problem: Freshly installed, when I read out my "Play Sound" preference with the following code:

defaults = [NSUserDefaults standardUserDefaults];
NSLog(@"Play Sounds? %d", [defaults boolForKey:@"play_sounds_preference"]);

The setting always reads out as false, even though the default setting is set to true. Any ideas? Here is my Root.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
<plist version="1.0">
<dict>
    <key>StringsTable</key>
    <string>Root</string>
    <key>PreferenceSpecifiers</key>
    <array>
        <dict>
            <key>Type</key>
            <string>PSGroupSpecifier</string>
            <key>Title</key>
                <string>General Settings</string>
            </dict>
            <dict>
                <key>Type</key>
                    <string>PSToggleSwitchSpecifier</string>
                    <key>Title</key>
                    <string>Sounds</string>
                    <key>Key</key>
                    <string>play_sounds_preference</string>
                    <key>DefaultValue</key>
                    <true/>
            </dict>
    </array>
</dict>
</plist>

When the user opens the Settings.app and navigates to my app's name, THEN the setting reads out as true, even if the user doesn't change anything.

+4  A: 

The default setting is only set when the user opens the settings app, unfortunately.

You could simply check that the key exists when you start the app, and set the default if it doesn't:

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"theKey"]){
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"theKey"];
}

Or, if you have a lot of keys that need setting, you can look at NSUserDefault's registerDefaults.

Tom Irving
awesome. Thanks.
winsmith
There a really nice piece of code in another SO question that helps with this by initializing the defaults based on your Root.plist. It's great because you don't have to set the defaults in two places. See: http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the-s
progrmr
Ooh, that is nice!
Tom Irving