Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you save an integer to NSUserDefaults?

Tags:

ios

iphone

Does anyone know how I would go about saving my high score integer to NSUserDefaults so I can load it later?


2 Answers

[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScore"];

… to get it back:

NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"];

This is explained very simply in the documentation.

like image 67
iKenndac Avatar answered Sep 14 '25 05:09

iKenndac


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.

like image 23
Alex Reynolds Avatar answered Sep 14 '25 06:09

Alex Reynolds