NSUserDefaults不更改默认值

时间:2012-03-08 20:40:31

标签: objective-c ios xcode

我问过一个最初回答here的问题。最初,我检查了第一个答案是最好的答案,但为了简单起见,我最终使用了NSUserDefaults。但问题是,在我在启动期间为其分配值时,即使我使用setObject: forKey:,有问题的默认值也不会改变。这是代码:

//In MenuViewController.m
- (void)viewDidLoad {

    NSDictionary* dictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:10] forKey:@"highscore"];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

    NSLog(@"%d", [[[NSUserDefaults standardUserDefaults] objectForKey:@"highscore"] intValue]);

    //Unrelated code

}

从那里开始游戏会话,当会话结束时,实现此代码:

-(void)timeUp{
    statsView= [[StatViewController alloc]initWithNibName:@"StatViewController" bundle:nil];
    statsView.score=score;
    int highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"highscore"] intValue];
    if (highScore < score)
    {
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:score] forKey: @"highScore"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSLog(@"%d", [[[NSUserDefaults standardUserDefaults] objectForKey:@"highscore"] intValue]);
    }
    highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"highscore"];
}

然后在StatViewController中:

//highScoreLabel is a UILabel that's set up through IB
highScoreLabel.text = [NSString stringWithFormat:@"%d",[[[NSUserDefaults standardUserDefaults] objectForKey:@"highscore"] intValue]];

我注册了NSUserDefaults,甚至使用了synchronize,但是控制台总是显示值为10.我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

键区分大小写!

您正在设置highScore,但您总是在highscore阅读。

答案 1 :(得分:1)

 [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:score] forKey: @"highScore"];

在此处设置分数时,请使用密钥@“highScore”。

当您阅读密钥时,使用@“highscore”。将第一个更改为@“highscore”,它应该可以工作。