为什么 NSUserDefaults 不能与我的 UISwitch 一起使用
我正在尝试设置一个默认关闭的 UISwitch,直到用户将其打开。但现在默认显示为 ON。
AppDelegate的didFinishLaunching:
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"pinCodeSwitch"];
if (!testValue) {
// since no default values have been set, create them here
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"pinCodeSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
VC的viewDidAppear:
UISwitch* testSwitch = [[[UISwitch alloc] init] autorelease];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pinCodeSwitch"]) {
[testSwitch setOn:NO animated:NO];
}
self.pinCodeSwitch = testSwitch;
UISwitch的值改变时保存BOOL的方法:
- (IBAction)pinCodeSwitchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"pinCodeSwitch"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:@"pinCodeSwitch"];
}
I'm trying to setup a UISwitch that is off by default until the user turns it on. However it is showing ON by default now.
AppDelegate's didFinishLaunching:
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"pinCodeSwitch"];
if (!testValue) {
// since no default values have been set, create them here
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"pinCodeSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
VC's viewDidAppear:
UISwitch* testSwitch = [[[UISwitch alloc] init] autorelease];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pinCodeSwitch"]) {
[testSwitch setOn:NO animated:NO];
}
self.pinCodeSwitch = testSwitch;
Method to save BOOL when UISwitch's value changed:
- (IBAction)pinCodeSwitchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"pinCodeSwitch"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:@"pinCodeSwitch"];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 Interface Builder 中通过将“STATE”值设置为 OFF 来指定该值。
然后通过应用此代码保存开关值:
当视图加载时,从默认值加载它,如下所示:`YourUiSwitch =
GOOD LUCK BUDDY!
you can specify this value in the Interface Builder by the "STATE" value to OFF.
and after that save the switch value by applying this code:
and when the view did load comes load it from the defaults like this:`YourUiSwitch =
GOOD LUCK BUDDY!
由于您将“pinCodeSwitch”设置为“否”,因此您无法设置开关。它会跳过 if 语句。
将其更改为:(
否定您的测试),然后开关将关闭。
You're not getting to set the switch since you set 'pinCodeSwitch' to NO. It skips the if statement.
Change it to:
(Negate your test), then the switch will turn off.