对于从NSUserDefaults检索的整数,始终获得0

时间:2014-04-30 23:00:26

标签: ios objective-c cocoa-touch nsuserdefaults

我有一个存储在用户默认值中的整数,用于我的游戏的高分。每次我开始游戏时我想检查分数是否大于之前的高分,所以我这样做:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:highScoreNum forKey:@"highScoreNumber"];

if (highScoreNum <= score) {
   highScoreNum = score;

   SKLabelNode *highLabel = (SKLabelNode *)[self childNodeWithName:@"highLabel"];
   highLabel.text = [NSString stringWithFormat:@"%ld", (long)highScoreNum];

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   [defaults setInteger:highScoreNum forKey:@"highScoreNumber"];
}
else if (highScoreNum > score) {
   SKLabelNode *highLabel = (SKLabelNode *)[self childNodeWithName:@"highLabel"];
   highLabel.text = [NSString stringWithFormat:@"%ld", (long)highScoreNum];

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   [defaults setInteger:highScoreNum forKey:@"highScoreNumber"];
}

在我声明变量的地方我这样做:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:highScore forKey:@"highScoreNumber"];
highLabel.text = [NSString stringWithFormat:highScore];

但我总是在highScoreNum获得0。

3 个答案:

答案 0 :(得分:2)

每次你这样做......

[defaults setInteger:highScore forKey:@"highScoreNumber"];

...您将highScore变量发送到默认值。如果您声明了highScore,但是之后没有获取以前保存的默认值(或者不以其他方式初始化highScore),那么为什么你在这里看到零是有道理的。您可能会继续将nil发送到默认值,默认值为整数值零(并返回)。

在声明* defaults之后,您可能希望让highScore存储默认值中的相应值,而不是调用setInteger:forKey,如下所示:

highScore = [defaults integerFromKey:@"highScoreNumber"];

另外,在适当的时候不要忘记[默认同步]。

答案 1 :(得分:0)

setInteger:forKey:

  

将指定的默认键的值设置为指定的整数   值。

因此,您的代码会在多个位置将值存储到NSUserDefaults。它永远不会读回一个值。

(你应该查看-synchronize

答案 2 :(得分:0)

试试这个

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:highScoreNum forKey:@"highScoreNumber"];
[defaults synchronize]; // force the upgrade NSUserDefaults
if (highScoreNum <= score) {
     highScoreNum = score;

     SKLabelNode *highLabel = (SKLabelNode *)[self childNodeWithName:@"highLabel"];
     highLabel.text = [NSString stringWithFormat:@"%ld", (long)highScoreNum];

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     [defaults setInteger:highScoreNum forKey:@"highScoreNumber"];
 }
 else if (highScoreNum > score) {
     SKLabelNode *highLabel = (SKLabelNode *)[self childNodeWithName:@"highLabel"];
     highLabel.text = [NSString stringWithFormat:@"%ld", (long)highScoreNum];

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     [defaults setInteger:highScoreNum forKey:@"highScoreNumber"];
     [defaults synchronize]; // force the upgrade NSUserDefaults
 }