Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

xcodeNewbie

macrumors member
Original poster
Jul 1, 2011
65
0
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:

Code:
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?
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
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"

Code:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.