有NSUserDefault问题

时间:2011-04-21 17:22:57

标签: iphone objective-c ios

我试图在一个程序中保存一些偏好,我似乎无法使NSUserDefaults正常工作。如果有人可以查看我的代码,看看是否有任何错误,将不胜感激

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

}

他们每次运行loadGameState方法时都会返回默认值,就像没有要引用的键一样。

1 个答案:

答案 0 :(得分:1)

在saveGameState中,我建议在默认值中添加同步以保留它们。如果您的游戏崩溃或者您正在停止调试器或其他任何错误,则可能无法正确保存。

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