2012-03-08 177 views
1

我问了一个关于这个问题的问题最初是回答here。最初,我将第一个答案作为最好的答案进行检查,但为了简单起见,我最终使用了NSUserDefaults。但问题是,在启动过程中为其分配一个值后,即使使用setObject: forKey:,相关的默认值也不会更改。下面的代码:NSUserDefaults不改变默认值

//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,甚至使用同步,但控制台总是显示值为10.我在这里做错了什么?

回答

2

键区分大小写!

您正在设置highScore,虽然您总是阅读highscore

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

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

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