Help with Saving High Score

Discussion in 'iOS Programming' started by xcodeNewbie, Jul 10, 2011.

  1. macrumors member

    Joined:
    Jul 1, 2011
    #1
    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?
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    You sure you want to be using two different key values: @"Hight Score" and @"High Score"?
     
  3. thread starter macrumors member

    Joined:
    Jul 1, 2011
    #3
    Saving HIgh Scores

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

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #4
    Rule #1 of troubleshooting. "Did you plug it in?" applies here. :p

    B
     
  5. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #5
    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.
     

Share This Page