views:

875

answers:

2

Hi,

I am working on an iPhone app

I read a key from root.plist like this :

NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:@"Key1"]; ("Key1" is a PSMultiValueSpecifier for which a default string value has been set already in root.plist)

That works fine, once the user makes settings. But if the user runs the app before he does any setting, he will get NIL for "Key1". In such case, I was expecting the default value that i had set for "key1". what i need to do, so that the user does not have to do setting, to make application run for the first time?

Regards, Harish

+1  A: 

I do this early after launch, before I try to get my settings:

 userDefaultsValuesPath=[[NSBundle mainBundle] pathForResource:@"UserDefaults"
                 ofType:@"plist"];
 userDefaultsValuesDict=[NSDictionary dictionaryWithContentsOfFile:userDefaultsValuesPath];

 // set them in the standard user defaults
 [[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValuesDict];

 if (![[NSUserDefaults standardUserDefaults] synchronize])
  NSLog(@"not successful in writing the default prefs");
mahboudz
But what if your path is the default "root.plist" in the settings.bundle?
Joe
Joe: Then you get a reference to that bundle and send it `-pathForResource:`. If you can't do that for whatever reason, you could just copy the plist into your app bundle's resources as well as into the settings bundle's.
Jeremy W. Sherman
A: 

In my application delegate, I override the +initialize method and register new application default preferences.

For example:

+ (void) initialize {
    if ([self class] == [MyAppDelegate class]) {     
        // initialize user defaults dictionary
        BOOL isFirstTimeRun = YES;
        BOOL isKeychainTurnedOn = NO;
        BOOL isSSLTurnedOn = YES;
        NSString *testURLString = @"http://stackoverflow.com";
        NSMutableDictionary *resourceDict = [NSMutableDictionary dictionary];
        [resourceDict setObject:[NSNumber numberWithBool:isFirstTimeRun] forKey:kIsFirstTimeRunKey];
        [resourceDict setObject:[NSNumber numberWithBool:isKeychainTurnedOn] forKey:kIsKeychainTurnedOnKey];
        [resourceDict setObject:[NSNumber numberWithBool:isSSLTurnedOn] forKey:kIsSSLTurnedOnKey];
        [resourceDict setObject:testURLString forKey:kTestURLString];
        [[NSUserDefaults standardUserDefaults] registerDefaults:resourceDict];
    }
}
Alex Reynolds
what if you have an actual settings.bundle and root.plist resource?
Joe