Reputation: 4732
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"];
}
Upvotes: 0
Views: 426
Reputation: 2363
You're not getting to set the switch since you set 'pinCodeSwitch' to NO. It skips the if statement. Change it to:
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"pinCodeSwitch"])
(Negate your test), then the switch will turn off.
Upvotes: 2
Reputation: 4079
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:
[YourUiSwitch setOn:NO animated:YES];
[[NSUserDefaults standardUserDefaults]setValue:YourUiSwitch forKey:@"youruiswitch"];
[[NSUserDefaults standardUserDefaults]synchronize];
and when the view did load comes load it from the defaults like this:`YourUiSwitch =
[[NSUserDefaults standardUserDefaults]valueForKey:@"youruiswitch"];`
GOOD LUCK BUDDY!
Upvotes: 1