好的,这对我来说看起来完全正确,但它有时会起作用,有时候不起作用。有没有更好的方法来做到这一点,还是我错过了什么?只是试图将高分保存到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"]);
}
这是日志输出。
// 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
答案 0 :(得分:1)
问题与NSUserDefaults
无关。
if (currentScore > newHighScore) ...
将指针与Objective-C对象进行比较。 您想要比较整数值:
if ([currentScore integerValue] > [newHighScore integerValue]) ...