Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...