save and load highscore

2019-01-25 21:30发布

问题:

i tried to use NSUserDefults to save and load a highscore(nsinteger) for my game. i created an void function that check if the gameoverscore is bigger than my highscore and if it does to switch between them. i want that every time the game is over there will be a label which show my currect highscore. to do this, i create a property for my NSUsweDefults, in my viewdidload i tried to load the currect highscore, and another function (checkIfHighscore). here is my NSUserDefults property:

@property(readwrite) NSUserDefaults *prefs;

here is my viewdidload code:

    NSInteger currectHighscore =  [prefs integerForKey:@"highscore"];
    highScoreLabel.text = [NSString stringWithFormat:@"%d",currectHighscore];

here is my checkIfHighscore:

-(void)checkIfHighScore
{
    if(gameOverScore > highScore)
    {
        highScore = gameOverScore;
        [self newHighscoreAnimation];

        [prefs setInteger:highScore forKey:@"highscore"];
        [prefs synchronize];

    }
    highScoreLabel.text = [NSString stringWithFormat:@"Highscore:  %d", highScore];
}

when i enter to this viewcontroller my highscorelabel shows 0, like it doesnt save my highscore.

what do i do wrong? thanks!

回答1:

// Snippet used to save your highscore in the prefs.
int highScore  = yourGameScore;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];


// Snippet used to get your highscore from the prefs.
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];