我正在做一个项目,我必须在settings.bundle中检索一些值。为此,我必须以这种方式检索默认值。 我在
下访问它NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
stringObject = [defaults objectForKey:@"Key_Value"];
但是当我尝试打印stringObject
时NSLog(@"%@",stringObject);
然后它总是打印null。 我已使用键“Key_Value”在settings.bundle中保存了一个字符串值。但它返回Null。
告诉我我做错了什么答案 0 :(得分:2)
检查你是否以这种方式存储了你的价值: -
NSUserDefaults *pref3=[NSUserDefaults standardUserDefaults];
[pref3 setObject:*yourstring* forKey:@"Key_Value"];
[NSUserDefaults resetStandardUserDefaults];
您的检索代码是正确的。确保string对象是NSString类型。
答案 1 :(得分: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];
}