本文介绍了保存并加载高分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用NSUserDefults为我的游戏保存并加载一个高分(nsinteger).我创建了一个void函数,用于检查gameoverscore是否大于我的高分,以及是否确实要在它们之间进行切换.我希望每次游戏结束时都会有一个标签,显示我目前的高分.为此,我为NSUsweDefults创建了一个属性,在我的viewdidload中,我尝试加载当前的高分和另一个函数(checkIfHighscore).这是我的NSUserDefults属性:

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

这是我的checkIfHighscore:

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

当我进入该视图控制器时,我的高分标签显示0,就像它不保存我的高分一样.

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

我做错了什么?谢谢!

what do i do wrong?thanks!

推荐答案

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

这篇关于保存并加载高分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:27