Help with Saving High Score

Discussion in 'iPhone/iPad Programming' started by xcodeNewbie, Jul 10, 2011.

  1. macrumors member

    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?
  2. Moderator


    Staff Member

    You sure you want to be using two different key values: @"Hight Score" and @"High Score"?
  3. macrumors member

    Saving HIgh Scores

    Lol thanks...I'm a noob. How embarrassing....
  4. Moderator


    Staff Member

    Rule #1 of troubleshooting. "Did you plug it in?" applies here. :p

  5. macrumors 68030


    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.

Share This Page