Search code examples
ios5uiswitch

Trouble setting UISwitch to stored NSUserDefaults value


I am running into a problem whereby I am unable to retain the state of a UISwitch in my app. I think the problem is I've been trying so many different examples from different tutorials and code sources to get this working, and I'm just not seeing the complete picture.

I've set up a user preferences screen, relevant code is:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Trying here to check whether user has run app previously, and if not set default switch value (as defined in IB)
NSString *firstRunValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"testSwitch"];
if (!firstRunValue) {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"testSwitch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

return YES;
}

OptionsViewController.h

@property (weak, nonatomic) IBOutlet UISwitch *testSwitch;

OptionsViewController.m

@synthesize testSwitch;

.
.
.

- (void)viewDidLoad
{

[super viewDidLoad];
// Here's the issue - following line does NOT set switch as expected from defaults...
[testSwitch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"testSwitch"] animated:NO];

}

.
.
.

- (IBAction)updateTest:(id)sender {
// Action called when switch is clicked to save new state, Log shows 0 or 1 as expected
[[NSUserDefaults standardUserDefaults] setBool:[sender isOn] forKey:@"testSwitch"];
NSLog(@"%@", [[NSUserDefaults standardUserDefaults]valueForKey:@"testSwitch"]);
}

.
.
.

- (IBAction)saveOptions:(id)sender {

// When user clicks "Save" and exits, I synch defaults and dump them, again output is as expected
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
[self dismissModalViewControllerAnimated:YES];
}

If someone could let me know where I'm going wrong (in English rather than in Objective-C!) I'd appreciate it, thanks!


Solution

  • Try this:

    NSString *firstRunValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"firstRun"];
    
    if (!firstRunValue) {
        [[NSUserDefaults standardUserDefaults] setObject: @"BlaBla" forKey:@"firstRun"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"testSwitch"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }