PDA

View Full Version : Help with Saving High Score




xcodeNewbie
Jul 10, 2011, 04:56 PM
I've made an app that plays Yahtzee. Everything works fine except for saving the user's high score. Here's the code that gets called when the user is out of turns:

highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"Hight Score"];
if (score>highScore) {
[[NSUserDefaults standardUserDefaults] setInteger:score forKey:@"High Score"];
[[NSUserDefaults standardUserDefaults] synchronize];
[highScoreLabel setText:[NSString stringWithFormat:@"High: %d", score]];
}

Every time the game end, the new high score always becomes the user's score for that game, even if they didn't beat the high score. Could someone please help me?



dejo
Jul 10, 2011, 05:08 PM
You sure you want to be using two different key values: @"Hight Score" and @"High Score"?

xcodeNewbie
Jul 10, 2011, 05:12 PM
Lol thanks...I'm a noob. How embarrassing....

balamw
Jul 10, 2011, 05:13 PM
Rule #1 of troubleshooting. "Did you plug it in?" applies here. :p

B

PhoneyDeveloper
Jul 10, 2011, 05:42 PM
You want to avoid duplicating values in multiple places in your code. Keys are one of the clearest examples of this. Use a constant for the key and then use that constant throughout the code.

#define kHighScoreKey @"high_score"

highScore = [[NSUserDefaults standardUserDefaults] integerForKey:kHighScoreKey];
if (score>highScore) {
[[NSUserDefaults standardUserDefaults] setInteger:score forKey:kHighScoreKey];
[[NSUserDefaults standardUserDefaults] synchronize];
[highScoreLabel setText:[NSString stringWithFormat:@"High: %d", score]];
}

The compiler will then tell you about any typos, and the type-ahead system will help you with inserting your values because it remembers them.