应用程序设置包 - ToggleSwitch

时间:2012-01-26 08:08:33

标签: objective-c ios ios5

我在应用设置中使用我的应用ToggleSwitch。我的设置在plist文件中。

Toggle Switch Elements are these:
Type (required) = Toggle Switch 
Title (required, localizable) = MyToggle 
Key (required) = enabled_preference 
DefaultValue (required) = (BOOL) YES;
 Value for ON = (BOOL) YES 
Value for OFF = (BOOL) NO

在应用程序中,我这样做是为了识别:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL enabled = [defaults boolForKey:@"enabled_preference"]; 
NSLog(@"enabled = %i",enabled);

但是当我第一次安装app时,Toggle Switch是ON,但启用= false。我不明白为什么?

也许有些人可以帮助如何在设置plist文件中进行本地化?

2 个答案:

答案 0 :(得分:4)

这是因为首次启动时,设置包中的设置尚未加载到NSUserDefaults。您必须编写一个方法来设置默认值并将其注册到registerDefaults,并将其添加到application:didFinishLaunchingWithOptions:或每次启动时执行的任何其他方法。

答案 1 :(得分:0)

将此代码添加到AppDelegate中的appdidfinishlaunching方法中,它会在首次启动时为您注册所有默认值。

- (void)registerDefaultsFromSettingsBundle
{
    /*
     before a user saves a nsdefault the entries in the settings bundle config file are not registereed.  
     The function loops through each preference in the root.plist of the settings.bundle file and registers each key that is not readable (therefore not registered).
     */
    //NSLog(@"Registering default values from Settings.bundle");
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    [defs synchronize];

    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];

    if(!settingsBundle)
    {
        NSLog(@"Could not find Settings.bundle");
        return;
    }

    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    if(!settings)
        return;

        NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
    if(!preferences)
        return;
        NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];

    for (NSDictionary *prefSpecification in preferences)
    {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if (key)
        {
            // check if value readable in userDefaults
            id currentObject = [defs objectForKey:key];
            if (currentObject == nil)
            {
                // not readable: set value from Settings.bundle
                id objectToSet = [prefSpecification objectForKey:@"DefaultValue"];
                [defaultsToRegister setObject:objectToSet forKey:key];
               // NSLog(@"Setting object %@ for key %@", objectToSet, key);
            }
                    }
    }

    [defs registerDefaults:defaultsToRegister];
    [defaultsToRegister release];
    [defs synchronize];
}