Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
616 views
Welcome To Ask or Share your Answers For Others

1 Answer

// 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 ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...