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.
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);
If the NSLog(@"[NSUSERDefaults] Score: %d", score);
code statement is uncommented, then the output will be as follows:
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
.
They also have corresponding retrieval functions to get the stored value.
3.139.97.53