1

我正在做一个项目,我必须在 settings.bundle 中检索一些值。为此,我必须以这种方式检索默认值。我正在访问它

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

stringObject = [defaults objectForKey:@"Key_Value"];

但是当我尝试打印 stringObject

NSLog(@"%@",stringObject);

然后它总是打印空。我在 settings.bundle 中保存了一个字符串值,键为“Key_Value”。但它返回 Null。

告诉我哪里做错了

4

2 回答 2

2

检查您是否以这种方式存储了您的价值:-

NSUserDefaults *pref3=[NSUserDefaults standardUserDefaults];
    [pref3 setObject:*yourstring* forKey:@"Key_Value"];
    [NSUserDefaults resetStandardUserDefaults];

您的检索代码是正确的。确保 stringObject 是 NSString 类型。

于 2011-06-13T09:43:57.267 回答
0

调用此函数将解决您的问题

- (void)registerDefaultsFromSettingsBundle {
     // this function writes default settings as settings
     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"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];

    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for(NSDictionary *prefSpecification in preferences) {
    NSString *key = [prefSpecification objectForKey:@"Key"];
    if(key) {
        [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
        NSLog(@"writing as default %@ to the key %@",[prefSpecification objectForKey:@"DefaultValue"],key);
    }

   [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];

}
于 2016-12-30T04:06:49.377 回答