I am trying to save a couple of preferences 开发者_Go百科in a program I can't seem to make NSUserDefaults work properly. If someone could take a look at my code and see if there are any errors it would be appreciated
NSString *kGameIsPaused = @"gameGameIsPaused";
NSString *kSoundOn = @"gameSoundOn";
NSString *kMusicOn = @"gameMusicOn";
NSString *kHighScore = @"gameHighScore";
- (void)saveGameState
{
[[NSUserDefaults standardUserDefaults] setBool:gameIsPaused forKey:kGameIsPaused];
[[NSUserDefaults standardUserDefaults] setBool:soundOn forKey:kSoundOn];
[[NSUserDefaults standardUserDefaults] setBool:musicOn forKey:kMusicOn];
[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:kHighScore];
}
-(void)loadGameState
{
gameIsPaused = [[NSUserDefaults standardUserDefaults] boolForKey:kGameIsPaused];
soundOn = [[NSUserDefaults standardUserDefaults] boolForKey:kSoundOn];
musicOn = [[NSUserDefaults standardUserDefaults] boolForKey:kMusicOn];
highScore= [[NSUserDefaults standardUserDefaults] integerForKey:kHighScore];
if (soundOn == NO) {
[soundToggle setImage:[UIImage imageNamed:@"SoundOFF.png"] forState:UIControlStateNormal];
}
if (musicOn == NO) {
[musicToggle setImage:[UIImage imageNamed:@"MusicOff.png"] forState:UIControlStateNormal];
}
}
they everytime i run the loadGameState method I get returned the default values as if there is no key to reference.
Inside of saveGameState I would recommend adding a synchronize to your defaults to persist them. If your game is crashing or you are stopping the debugger or anything else goes wrong they may not get saved properly.
- (void)saveGameState
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:gameIsPaused forKey:kGameIsPaused];
[defaults setBool:soundOn forKey:kSoundOn];
[defaults setBool:musicOn forKey:kMusicOn];
[defaults setInteger:highScore forKey:kHighScore];
[defaults synchronize];
}
精彩评论