Using NSUserDefaults

NSUserDefaults is a simple way of storing basic information, such as scores and current level, that is not too heavy on code . All you have to do is provide the value and key while storing the data. Later, when you wish to retrieve the data, all you have to do is provide the key, and the data will be retrieved.

Let's take a look at how to use this.

How to do it…

Let's suppose we want to store the high score value. We will have to do the following:

intcurrentHighScore = 24;

[[NSUserDefaultsstandardUserDefaults] setInteger:currentHighScoreforKey:@"highScore_key"];
[[NSUserDefaultsstandardUserDefaults] synchronize];

It is important to synchronize because otherwise if we shut down the application and reopen it, the data will be lost. To save the data onto the device, it is best to call synchronize.

To retrieve the information, we need to do the following:

int score = [[NSUserDefaultsstandardUserDefaults] integerForKey:@"highScore_key"];

NSLog(@"[NSUSERDefaults] Score: %d", score);

How it works…

If the NSLog(@"[NSUSERDefaults] Score: %d", score); code statement is uncommented, then the output will be as follows:

How it works…

This just logs the current value stored in the highScore_key key.

You are not restricted to storing only integer types. You can also store Boolean, double, and float.

How it works…

They also have corresponding retrieval functions to get the stored value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53