1

I am doing a project where I have to retrieve some values in settings.bundle. For this I have to retrieve a default value in such a manner. I am accessing it as under

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

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

But when I try to print stringObject

NSLog(@"%@",stringObject);

Then it always print null. I have saved a string value in the settings.bundle with key "Key_Value". But It returns Null.

tell me where I am doing wrong

Sanchit Paurush
  • 6,114
  • 17
  • 68
  • 107
  • 6
    possible duplicate of [How to retrieve values from settings.bundle in objective c?](http://stackoverflow.com/questions/6291477/how-to-retrieve-values-from-settings-bundle-in-objective-c) – Vladimir Jun 13 '11 at 09:40
  • Please post code showing how you set the value initially. Also, remember to synchronize UserDefaults after settings values. – Alfie Hanssen Apr 29 '13 at 18:51

2 Answers2

2

check you have stored you value in this way:-

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

your code of retreiving is correct.make sure stringObject is of NSString type.

Gypsa
  • 11,230
  • 6
  • 44
  • 82
  • @sanchitsingh I am curious to know whether your problem is sorted out or not. – Gypsa Jun 13 '11 at 10:42
  • I think you misunderstood the question. He stores the data in Settings.bundle [here](http://stackoverflow.com/questions/6291477/how-to-retrieve-values-from-settings-bundle-in-objective-c) you can find out what was the correct answer – Julian Oct 22 '15 at 14:20
0

Call this function will resolve your issue

- (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];

}