How would I go about locally saving variables so that I can access them each time an application is run? An example would be saving high scores for a game or settings for an app. The application needs to be able to access the variables each time it runs and the memory shouldn't be released. Should I use the NSUserDefaults class or are there other options?
Asked
Active
Viewed 68 times
0
-
Related: [Working with data in iOS Apps](http://stackoverflow.com/q/10244782/335858). – Sergey Kalinichenko Jul 22 '13 at 17:11
-
1NSUserDefaults would do it for you. If the data to be saved is huge, than use Core Data. – Puneet Sharma Jul 22 '13 at 17:11
2 Answers
1
For big amounts of data or data stored like a database (for example, related data), use CoreData.
For small objects, use NSUserDefaults.

Antonio MG
- 20,382
- 3
- 43
- 62
-
1I would add that for medium size data (NSdictionary will a bunch of keys), you can use NSKeyedArchieve. Simple to use without all the pain of CoreData. – John Jul 22 '13 at 19:26
1
For small amounts of data, such as simply storing numbers as a high score, NSUserDefaults should be enough. Here's some code to get you started:
//Save High Scores
NSMutableArray *array = [NSMutableArray arrayWithCapacity:3];
array[0] = highScore1;
array[1] = highScore2;
array[2] = highScore3;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:array forKey:@"highScores"];
//load high scores
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSArray *array = [prefs objectForKey:@"highScores"];
HighScore1Label.text = array[0];
//etc

Matthew Griffin
- 381
- 2
- 11