虽然 NSUserDefaults 的代码看起来很简单,但我无法让它工作。
我有一个设置视图,用户可以在其中禁用或不禁用声音。这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.soundSettings.font = [UIFont rw_snapFontWithSize:24.0f];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:@"stateForSoundSwitch"]) {
NSLog(@"Sound is ON");
self.soundStatus.on=YES;
} else {
self.soundStatus.on=NO;
NSLog(@"Sound is OFF");
}
}
- (IBAction)soundSwitchChanged:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (self.soundStatus.on) {
NSLog(@"Sound is enabled");
[defaults setBool:true forKey:@"stateForSoundSwitch"];
}
else {
NSLog(@"Sound is disabled");
[defaults setBool:false forKey:@"stateForSoundSwitch"];
}
[defaults synchronize];
}
但即使我将开关更改为 FALSE,每次我登录设置屏幕时,值都是 TRUE。我错过了什么?