iPhone Dev : Persisting Values

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.

Advertisements

One Response to iPhone Dev : Persisting Values

  1. Pingback: iPhone Dev : Persisting Values | Tea Break

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: