Reputation: 553
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?
Upvotes: 1
Views: 551
Reputation: 610
[[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.
Upvotes: 1
Reputation: 1682
Keys are case sensitive!
You're setting highScore
although you always read in highscore
.
Upvotes: 2