Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save And Load A Single Value, iPhone

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

like image 920
Stumf Avatar asked Dec 04 '22 13:12

Stumf


1 Answers

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];
like image 131
Giao Avatar answered Dec 11 '22 10:12

Giao