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

iPhone Dev : Turning Sound On/Off in Cocos2d/CocosDenshion

Well its a pretty basic requirement in game development but for the very first time you don’t exactly know how to do it.Naturally i went to Cocos2d website and looked in cocosdension help.Here is the way to do this mentioned on cocos2d website

   1: [CDAudioManager sharedManager].backgroundMusic.volume = 1.0f;

Range is 0.0 for off to 1.0 for maximum volume.

But when your using multiple background sounds this way gets a little messy.Something to do with the fact that for very sound file you have to reset the music volume and previous music volume value does not persists.So natural i banged my head quite a lot on how to fix this.

After few hours of head banging i just jumped into the code file and found an extremely easy way to mute/unmute sounds.

   1: [CDAudioManager sharedManager].mute = FALSE; //Sound On

   2: [CDAudioManager sharedManager].mute = TRUE;  //Sound Of

That’s it just one line and your settings last all across your app even if your using multiple sound files with [CDAudioManager sharedManager].This is the best way to implement if you have a settings screen in your game where you can turn sounds on/off.Basic stuff but is really helpful once you know it.