Does anyone know how I would go about saving my high score integer to NSUserDefaults so I can load it later?
Asked
Active
Viewed 2.4k times
2 Answers
58
[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScore"];
… to get it back:
NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];
This is explained very simply in the documentation.

iKenndac
- 18,730
- 3
- 35
- 51
-
10You are right, of course. But Googling (and finding useful two-line solutions like your's) is MUCH faster than digging through Apple's documentation. You could argue that, by Googling, I'm either lazy, or efficient..! – Mike Gledhill Apr 25 '14 at 13:14
10
More generally, you can save Foundation class objects to the user defaults, e.g.:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"kHighScore"];
and
NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];
But the convenience method is there for taking in an NSInteger
directly.
I prefer to use the more agnostic -setObject:
and -objectForKey:
because it more cleanly separates the object type from access to the dictionary.

Alex Reynolds
- 95,983
- 54
- 240
- 345