gpt4 book ai didi

iphone - 遇到 NSUserDefault 问题

转载 作者:行者123 更新时间:2023-11-29 13:49:15 24 4
gpt4 key购买 nike

我试图在我似乎无法使 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 方法时都会返回默认值,就好像没有要引用的键一样。

最佳答案

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

关于iphone - 遇到 NSUserDefault 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com