3

我最近几天一直在努力解决一个问题。我有一个设置包 root.plist,其中包含一些用户首选项。其中包含三个多值菜单项。一个返回布尔值,另外两个返回数字。

当我在控制台中调用[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]并检查它时,只有属性列表中的第一项显示它的值。其他两个明显缺席。结果,当我尝试检索这些值时,我得到零。

更奇怪的是,设置包在 iPhone 的“设置”应用中看起来是正确的。唯一不起作用的是值没有被传递。就我的应用而言,其他两个多值菜单项甚至都不存在。

非常感谢任何建议。

4

2 回答 2

6

我已经多次使用这个代码块applicationDidFinishLaunchingWithOptions来初始化我的用户默认值。

    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]; 
} 
于 2011-10-19T18:32:21.777 回答
2

确保您使用- (void)registerDefaults:(NSDictionary *)dictionary的是NSUserDefaults. 否则,您的默认值将不会从 Bundle 中提取。

在您尝试检索任何默认值之前,您必须在应用程序的早期执行此操作。

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

于 2011-10-19T18:25:04.213 回答