Instead of:
int highScore=(int)[userDefaults objectForKey:@"HighScore"];
You need to do
int highScore = [userDefaults integerForKey:@"HighScore"];
Pergunta
I am making a game using SpriteKit. The first time I lose the game, the high score is 0 (good). Then, I save the current score. The next time I play, the high score is a big number, for example 366508176. Why did this happens and any idea of how can I fix it?
This is the ScoreScene.m file, it superclass is SKScene. [GameScene getScore] is a static function that returns the last score.
//
// ScoreScene.m
//
#import "ScoreScene.h"
#import "GameScene.h"
@interface ScoreScene()
@property BOOL contentCreated;
@end
@implementation ScoreScene
-(void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated=YES;
}
}
-(void)createSceneContents
{
self.backgroundColor=[SKColor purpleColor];
self.scaleMode=SKSceneScaleModeAspectFill;
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
int highScore=(int)[userDefaults objectForKey:@"HighScore"];
//highScore is 0 the first time, 366508176 the second
int currentScore=[GameScene getScore];
//currentScore is 3, for example
if (currentScore>highScore) {
[userDefaults setInteger:currentScore forKey:@"HighScore"];
[userDefaults synchronize];
highScore=currentScore;
}
[self addChild:[self newHighScoreLabel:highScore]];
[self addChild:[self newScoreLabel]];
[self addChild:[self newStartLabel]];
}
...
@end
Solução
Instead of:
int highScore=(int)[userDefaults objectForKey:@"HighScore"];
You need to do
int highScore = [userDefaults integerForKey:@"HighScore"];
Outras dicas
Set:
[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:@"HighScore"]
Get:
[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]
Or, it's a little more general purpose to "wrap" scalars in NSNumbers, which would give you:
[defaults setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
and
int HighScore = [[defaults objectForKey:@"HighScore"] intValue];
A benefit of this is that the object is now easily placed in collections, passed in notifications, etc.