Reputation: 2735
This is supposed to save the value of two UISwitches to NSUserDefaults and then set the switches on load based on the values saved to the defaults. I've been at this for hours but I can't seem to get it to work. Any help would be greatly appreciated.
The toggles are in a View that I'm using for settings. There are only two toggles, so I want to use NSUserDefaults. Toggles default to OFF. I want to toggle to ON and have that change be saved so that I can change the User experience based on the toggle's value. Then, when the User opens the settings again, I want them to display their current saved state.
I think that the value is being saved, but it is not being applied to the Switches when I reenter the Settings View.
- (IBAction)setBeadVibratorBySwitchState:(id)sender
{
if (setBeadVibrator.selected == YES) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:NO forKey:@"beadSwitchStatus"];
[beadSettings synchronize];
}
if (setBeadVibrator.selected == NO) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:YES forKey:@"beadSwitchStatus"];
[beadSettings synchronize];
}
NSLog(@"Bead Executed");
}
- (IBAction)setDecadeVibratorBySwitchState:(id)sender
{
if (setDecadeVibrator.selected == YES) {
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:NO forKey:@"decadeSwitchStatus"];
[decadeSettings synchronize];
}
if (setDecadeVibrator.selected == NO){
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:YES forKey:@"decadeSwitchStatus"];
[decadeSettings synchronize];
}
NSLog(@"Decade Executed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
setBeadVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"beadSwitchStatus"];
setDecadeVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"decadeSwitchStatus"];
}
Upvotes: 1
Views: 1564
Reputation: 886
NSUserDefaults can only store objects of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. So, I suggest that you put the state of the switch in an NSString and put that string in the NSUserDefaults. Than when you retrieve the info from the NSUserDefaults, you can use an if statement to set the value of the boolean again.
Upvotes: 1
Reputation: 1818
I would suggest that you put the NSLog statements in the if-statements to see if they are really saved. If not, your UISwitches may not be configured properly with the UIControlEventValueChanged event.
You can read up more from Apple doc. Here is a very detailed website on using UISwitches.
Upvotes: 0
Reputation: 1740
If you are using UISwitch, you should set the on
property, instead of selected
.
setBeadVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"beadSwitchStatus"];
setDecadeVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"decadeSwitchStatus"];
Upvotes: 1