views:

99

answers:

2

Hello all,

I have a feeling there is a simple way to do this. I have a number between 1 and 100 and it is stored in a variable called firstValue. This variable is then put into a UILabel. When the user exits my app, I want this firstValue to be saved so that when the app is loaded by the user this number can be re-inserted into the UILabel (firstValueLabel.text).

Many thanks,

Stuart

+3  A: 

Hi, you can use the NSUserDefaults to store some variable for your application to retrieve them after a close of the application. For exemple:

// Set the name of the view
[[NSUserDefaults standardUserDefaults] setInteger:10 forKey:@"firstValue"];

To retrieve the last action of the user:

// Retrieve the last view name
Integer firstValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"firstValue"];

But you can add other than a integer. (see the NSUserDefaults Class Reference)

Yannick L.
+7  A: 

You can use NSUserDefaults for this.

To save it:

NSInteger myValue = ...; // This is your number
NSString *key = ... ; // This is a string to identify your number
[[NSUserDefaults standardUserDefaults] setInteger:myValue forKey:key];

To read it:

NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:key];

If no previous value has been saved, the value returned will be 0.

Add this to your applicationWillTerminate:

[[NSUserDefaults standardUserDefaults] synchronize];
Giao
It is better to call the `synchronize` method after you have changed the value. Just in case your app crashes or stops for some other reason.
St3fan