iPhone Dev : Persisting Values
January 30, 2010 1 Comment
Well i think most of us rely upon using SQLite for storing variables and data for our iPhone apps,but what if we only want to score 2-3 values.Like high score in some game or the number of visits to app.Setting up whole SQLite for just 2-3 variables doesn’t seem logical.
To solve this we use [NSUserDefaults standardUserDefaults].Basically this is used to store the default values and can also be used to save values associated with keys.
To Save Variables:
1: if([[NSUserDefaults standardUserDefaults] stringForKey:@"HighScore"])
2: {
3: int score = 250;
4: NSString *string = [NSString stringWithFormat:@"%d", score];
5: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
6: [defaults setObject:string forKey:@"HighScore"];
7: [defaults synchronize];
8: }
So if you have a HighScore value you can save it for some key,in this case”HighScore”.
To Retrieve Variables:
1: if ([[NSUserDefaults standardUserDefaults] stringForKey:@"HighScore"]){
2: NSString * highScore = [[NSUserDefaults standardUserDefaults] stringForKey:@"HighScore"];
3: }
And that’s it.Simple and no need to setup SQLite for storing your simple variables.