NSUserDefaults不会永久保存
我有一个相当简单的iPhone应用程序,我正在做。但是,我无法让我的NSUserDefaults永久保存。写入和检索数据不是问题 - 我可以保存数据(在我的情况下是一个字符串),并在命令中检索它,即使在切换视图,关闭/打开应用程序等之后,数据也只是被检索到精细。看起来好像字符串已正确保存到密钥中。但是,当我从多任务托盘中退出应用程序并重新启动它时,设置不再保存,应用程序就像第一次启动一样。我是一个新手程序员,所以这可能只是我的一个愚蠢的错误。NSUserDefaults不会永久保存
这里的储蓄是什么样子:
if (optionsSoundBox.center.x >= 240)
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.2];
self.soundOnLabel.alpha = 1;
self.soundOffLabel.alpha = 0;
[UIView commitAnimations];
NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults];
[soundOptions setObject:@"SoundsON" forKey:@"SoundKey"];
[soundOptions synchronize];
}
if (optionsSoundBox.center.x < 240)
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.2];
self.soundOnLabel.alpha = 0;
self.soundOffLabel.alpha = 1;
[UIView commitAnimations];
NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults];
[soundOptions setObject:@"SoundsOFF" forKey:@"SoundKey"];
[soundOptions synchronize];
}
我找回在viewDidLoad中的字符串,所以这将是准备在启动时是这样的:
NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults];
NSString *savedSoundSettings = [soundOptions stringForKey:@"SoundKey"];
if (savedSoundSettings == @"SoundsON")
{
[optionsSoundBox setCenter:CGPointMake(280, optionsSoundBox.center.y)];
}
if (savedSoundSettings == @"SoundsOFF")
{
[optionsSoundBox setCenter:CGPointMake(200, optionsSoundBox.center.y)];
}
我真的很感激任何帮助,您可以给
您应该使用[savedSoundSettings isEqualToString:@"SoundsON"]
,而不是使用double equals运算符。 (==
)。
除此之外,它可能是你在viewDidLoad
里面运行这个代码的事实。尝试在viewWillAppear
之内运行它。
最后,我建议使用camelcase名称作为设置键,所以长时间输入会更容易。 (想想soundsOn
而不是SoundsON
。)
您不应该将字符串与==
进行比较。比较字符串的正确方法是通过isEqualToString:
。所以,你如果在获取用户默认语句应该是这样的:
if ([savedSoundSettings isEqualToString:@"SoundsON"])
{
....
}
编辑:此外,在概念上,你正在检查是一个单一的状态变量是否开启或关闭。所以你最好应该使用类似[NSUserDefaults setBool:forKey:]
和[NSUserDefaults boolForKey:]
。
又因为你得到stringForKey:
代替objectForKey:
也许它会如果你只是使用[[NSUserDefaults standardUserDefaults] setBool: YES forKey: @"SoundsON"];
,然后检查是否boolForKey: @"SoundsON"
是真心对你会更容易。