jmeringer
jmeringer

Reputation:

How do I store program variables in an iPhone application that will survive a program exit?

I need to keep program variable values in an iPhone application when the application is exited. Does the SDK give the programmer any non volitile memory to use? How much is available? Will it be kept thru a power cycle? Through sleep mode? Through a hard reset?

Upvotes: 2

Views: 2544

Answers (5)

angelfilm entertainment
angelfilm entertainment

Reputation: 1163

-(void)saveToUserDefaults:(NSString*)myString
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"Prefs"];
        [standardUserDefaults synchronize];
    }
}

-(NSString*)retrieveFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *val = nil;

    if (standardUserDefaults) 
        val = [standardUserDefaults objectForKey:@"Prefs"];

    return val;
}

Upvotes: 2

lostInTransit
lostInTransit

Reputation: 70997

There are many options available for storing the data from your app to be used later. Tow of them as pointed out are using NSUserDefaults and SQLite. Another way is to create a file in the "Documents" folder of your app and save your data here. Read the contents of the file the next time the app is launched. This is explained in the Files & Networking guide from Apple

Even if using the database, make sure you create a copy of the database in the Documents folder of your app's sandbox so it persists even when you release an update for your app.

Upvotes: 3

Marc Novakowski
Marc Novakowski

Reputation: 45398

You want to use the NSUserDefaults class to store user settings. It's super easy. They will be persisted across device restarts, power cycles, etc.

Here's a short tutorial to get you started.

Upvotes: 4

Dave
Dave

Reputation: 1569

Your best option is to store them to into the your applications SQLite DB instance. Thats as close as you'll get to non volatile memory.

Upvotes: 0

Gordon Wilson
Gordon Wilson

Reputation: 26384

You could write to your app's local storage area or use a sqlite database. Both options are documented here, http://developer.apple.com/iphone/library/codinghowtos/DataManagement/index.html#FILE_MANAGEMENT-WRITE_INFORMATION_LOCALLY

Upvotes: 3

Related Questions