Wednesday, April 25, 2012

Add Settings to an iOS project

Just find a very nice article about the subject: 
Adding a settings bundle to an iPhone App 

Please pay attention on the paragraph "Even defaults need defaults…" - that's what I needed in my app. Recently I found out that the default values I set for the settings do not work - a boolean parameter is always NO and does not matter that I set it to YES. This boolean parameter gets its default value only when the user opens the application settings for the first time. This article proposes a solution.

The source documentation in the iOS Developer Library: 
Preferences and Settings Programming Guide 

iOS Developer Library proposes an example: FunHouse. Here is a method from this sample:


+ (void)setupDefaults
{
    NSDictionary *userDefaultsValuesDict;
    userDefaultsValuesDict=[NSDictionary dictionaryWithObject:
              [NSNumber numberWithBool:NOforKey:@"useSoftwareRenderer"];
    
    // set them in the standard user defaults
    [[NSUserDefaults standardUserDefaults
              registerDefaults:userDefaultsValuesDict];
}
Looks promising.
(Do not forget to uninstall your app from the phone and then install again in order to test changes in this code.)

In my app, I just expect that all boolean values from the app preferences are NO by default. My code looks so:

- (void)loadDebugSettings
{
    self.cleanBackupOn = NO;
    self.devServer = NO;
    self.logCommunicationOn = NO;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ( defaults )
    {
        self.cleanBackupOn = [defaults boolForKey:@"AutoCleanBackupData"];
        self.devServer = [defaults boolForKey:@"DevServerOn"];
        self.logCommunicationOn = ![defaults boolForKey:@"LogCommunicationOf"];
    }
}

Now, if I need one of these values to be YES, I use registerDefaults:

No comments:

Post a Comment