Setting.app裡面的app settings要注意耶

我看到plist裡面有個叫DefaultValue就以為會幫我handle埋default的情況於是好興奮的去用了 結果原來是,未設定過的話 [[NSUserDefaults standardUserDefaults] whateverForKey:]會return nil 仲要係若無其事的感覺,因為我沒看doc的關係抵死XD

於是以下是解決方法:http://www.btjones.com/2010/05/nsuserdefaults-nil-setting-problem/

- (void)setupDefaults {
    //get the plist location from the settings bundle
    NSString *settingsPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Settings.bundle"];
    NSString *plistPath = [settingsPath stringByAppendingPathComponent:@"Root.plist"];

    //get the preference specifiers array which contains the settings
    NSDictionary *settingsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    NSArray *preferencesArray = [settingsDictionary objectForKey:@"PreferenceSpecifiers"];

    //use the shared defaults object
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    //for each preference item, set its default if there is no value set
    for(NSDictionary *item in preferencesArray) {

        //get the item key, if there is no key then we can skip it
        NSString *key = [item objectForKey:@"Key"];
        if (key) {

            //check to see if the value and default value are set
            //if a default value exists and the value is not set, use the default
            id value = [defaults objectForKey:key];
            id defaultValue = [item objectForKey:@"DefaultValue"];
            if(defaultValue && !value) {
                [defaults setObject:defaultValue forKey:key];
            }
        }
    }

    //write the changes to disk
    [defaults synchronize];
}

適當的在application:didFinishLaunchingWithOptions: 裡面觸發就很好了