In my header file, I might add the following:
@interface myAppDelegate : NSObject <UIApplicationDelegate> {
...
NSString *databaseName;
}
extern NSString * const kDefaultDatabaseName;
extern NSString * const kAppDatabaseNameKey;
In my implementation file, I would add the following:
NSString * const kDefaultDatabaseName = @"myDefaultDatabaseName";
NSString * const kAppDatabaseNameKey = @"kAppDatabaseNameKey";
@implementation myAppDelegate
+ (void) initialize {
if ([self class] == [MyAppDelegate class]) {
UIApplication* myApp = [UIApplication sharedApplication];
NSString *defaultDatabaseName = kDefaultDatabaseName;
NSMutableDictionary *resourceDict = [NSMutableDictionary dictionary];
[resourceDict setObject:defaultDatabaseName forKey:kAppDatabaseNameKey];
}
}
- (void) applicationDidFinishLaunching:(UIApplication *)application {
...
databaseName = [[NSUserDefaults standardUserDefaults] stringForKey: kAppDatabaseNameKey];
}
...
- (void) applicationWillTerminate:(UIApplication *)application {
...
[[NSUserDefaults standardUserDefaults] setObject:databaseName forKey:kAppDatabaseNameKey]
}
When your application starts, if there are no pre-existing user defaults, +initialize
creates a fresh NSUserDefaults
dictionary with whatever you set to be your default database in kDefaultDatabaseName
.
When the application finishes launching, the member databaseName
takes on the value set in the NSUserDefaults
dictionary. This can be the kDefaultDatabaseName
or whatever it has been updated to after running your application.
While you run your application, your user may change the value of databaseName
to something else.
Just before the application terminates, the value of databaseName
is written to the NSUserDefaults
dictionary. The next time the application is opened, databaseName
will take on the new, updated value.
You don't have to wait for the application to terminate before writing this update to the dictionary. You could, for example, do this immediately after the user changes databaseName
to something new. But that's up to you.