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

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

objective c - save and load highscore

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

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

1 Answer

0 votes
by (71.8m points)
// 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 ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...