The problem is unrelated to NSUserDefaults
.
if (currentScore > newHighScore) ...
compares the pointers to the Objective-C objects. You want to compare the integer values:
if ([currentScore integerValue] > [newHighScore integerValue]) ...
문제
Ok, This all looks completly correct to me, but it's working sometimes, and not working sometimes. Is there a better way of doing this or am I missing something? Just trying to save High score to NSUserDefaults!
-(void)updateScore
{
NSString * currentScore = _scoreLabel.string;
NSLog(@"Current Score, %@", _scoreLabel.string);
NSString * newHighScore = _highScoreLabel.string;
NSLog(@"High Score, %@", _highScoreLabel.string);
if (currentScore > newHighScore) {
NSLog(@"updating high score!");
_highScoreLabel.string = currentScore;
NSUserDefaults *scoreDefaults = [NSUserDefaults standardUserDefaults];
[scoreDefaults setObject:_highScoreLabel.string forKey:@"high_Score"];
[scoreDefaults synchronize];
}
// string for key.
NSLog(@"Saved High Score, %@",[[NSUserDefaults standardUserDefaults] stringForKey:@"high_Score"]);
}
Here is the log output.
// Worked ok here.
2014-04-04 13:58:46.921 [2378:60b] game over
2014-04-04 13:58:46.923 [2378:60b] Current Score, 5
2014-04-04 13:58:46.924 [2378:60b] High Score, 4
2014-04-04 13:58:46.925 [2378:60b] updating high score!
2014-04-04 13:58:46.929 [2378:60b] Saved High Score, 5
// Worked ok here. Did not update score because it was less than high score.
2014-04-04 13:59:01.321 [2378:60b] game over
2014-04-04 13:59:01.323 [2378:60b] Current Score, 1
2014-04-04 13:59:01.325 [2378:60b] High Score, 5
2014-04-04 13:59:01.326 [2378:60b] Saved High Score, 5
// Did NOT WORK, current score was higher than saved high score.
2014-04-04 13:59:22.087 [2378:60b] game over
2014-04-04 13:59:22.089 [2378:60b] Current Score, 6
2014-04-04 13:59:22.092 [2378:60b] High Score, 5
2014-04-04 13:59:22.093 [2378:60b] Saved High Score, 5
해결책
The problem is unrelated to NSUserDefaults
.
if (currentScore > newHighScore) ...
compares the pointers to the Objective-C objects. You want to compare the integer values:
if ([currentScore integerValue] > [newHighScore integerValue]) ...