views:

1505

answers:

2

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.

+8  A: 

NSUserDefaults is the best place for settings like this.

Marc Charbonneau
+3  A: 

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.

Alex Reynolds