简体   繁体   中英

NSUserDefaults not changing default value

I asked a question about this that was originally answered here . Originally, I checked the first answer as the best one, but for the sake of simplicity, I ended up using NSUserDefaults . The problem, though, is that the default value in question is not changing after I assign it a value during startup, even when I use setObject: forKey: . Here's the code:

//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

}

From there, a game session runs, and when the session is over, this code is implemented:

-(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"];
}

And then in StatViewController:

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

I've registered the NSUserDefaults and even use synchronize, but the console always shows the value being 10. What am I doing wrong here?

Keys are case sensitive!

You're setting highScore although you always read in highscore .

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

When you are setting the score here, you use the key @"highScore".

When you read the key, you use @"highscore". Change the first one to @"highscore" and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM