Hi,
What is the easiest way to save a couple of variables in an iPhone application in a long-term memory?
I have an application that works with different sqlite databases and I want after exiting from an application to save last active database name in order to open last database when user enters an application again.
It's a little bit no convenient to create for this purpose a special database and store those values in it, because I have only a couple of variables to store.
What is the easiest way to store those variables?
Thank you in advance.
-
NSUserDefaults is the best place for settings like this.
-
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,
+initializecreates a freshNSUserDefaultsdictionary with whatever you set to be your default database inkDefaultDatabaseName.When the application finishes launching, the member
databaseNametakes on the value set in theNSUserDefaultsdictionary. This can be thekDefaultDatabaseNameor whatever it has been updated to after running your application.While you run your application, your user may change the value of
databaseNameto something else.Just before the application terminates, the value of
databaseNameis written to theNSUserDefaultsdictionary. The next time the application is opened,databaseNamewill 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
databaseNameto something new. But that's up to you.
0 comments:
Post a Comment