user1626438
user1626438

Reputation: 133

How to locally save objects?

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?

Upvotes: 0

Views: 71

Answers (2)

Matthew Griffin
Matthew Griffin

Reputation: 391

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

Upvotes: 1

Antonio MG
Antonio MG

Reputation: 20410

For big amounts of data or data stored like a database (for example, related data), use CoreData.

For small objects, use NSUserDefaults.

Upvotes: 1

Related Questions