Reputation: 280
in my game i use NSUserDefults to save the user highscore. in the first time i finushed the game my highscore is set to the game score, but every time after that the score in the game is automatically set as the highscore. the weirdness here is that id my game score is 0 then my highscore is stay as the biggest score, but if in the end of some game my score is 100 is sets as highscore but a game after that if my score is 50 my highscore is sets as 50(although the score was lower then my highscore). here is my viewdidload code:
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
highScoreLabel.text = [NSString stringWithFormat:@"%d",highScore];
here is my checkIfHighscore code:
-(void)checkIfHighScore
{
if(gameOverScore > highScore)
{
highScore = gameOverScore;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
highScoreLabel.text = [NSString stringWithFormat:@"%d", highScore];
}
what is the problem?
Upvotes: 1
Views: 155
Reputation: 23359
Your highScore loaded form NSUserDefaults
is going to be an Object
of type id
, you should cast it to NSNumber
, secondly in your checkIfHighScore
method, you should compare highScore.intValue
to gameOverScore
, and then:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:gameOverScore] forKey:@"HighScore"];
Notice how you are mixing number objects and scalar types (int
), you can't use the <
and >
operators, or even ==
between an Object
and a scalar variable.
Upvotes: 1