Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Eduardo Rojas
Eduardo Rojas
4,084 Points

How does NSUserDefault works

because i got to save the value and update it for the time the app is opened but whenever i close the app the value is not updated, I'm setting up a high Score

1 Answer

Stone Preston
Stone Preston
42,016 Points

first you need to grab the standard user defaults, then just set the integer for the key you want to save it as:

NSInteger highScore = 1000;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:highScore forKey:@"highScore"];

that will save the high score to the standard user defaults.

If you want to read the high score from the defaults, just grab the defaults again and use the integerForKey method to retrieve the data using the same key you saved it under

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger savedHighScore = [defaults integerForKey:@"highScore"];

its as simple as that.

generally its not a good idea to use NSUserDefaults to store data like high scores and what not, but its definitely the easiest way. NSCoding is a good way to save data like high scores and stuff. Here is a decent tutorial on how to use NSCoding

Eduardo Rojas
Eduardo Rojas
4,084 Points

Thank You but the problem was that it was not synchronizing so i just added the synchronize command and that was enough thank you anyways