Hubert Mane
Hubert Mane

Reputation: 13

Save UISwitch Status - Objective C

I know this has been asked before but I have yet to find a solution to this. I am attempting to save UISwitch state so that no matter which VC I enter, that switch state is still active. However, anytime I leave the VC the switch is in, it's resorts to off. Currently this is the code I'm using to save the switch state:

- (IBAction)tvpSwitch:(UISwitch *)sender {
    if (sender.isOn) {
    [[NSUserDefaults standardUserDefaults]setObject:@"on" forKey:@"tvpSwitch"];
    [[NSUserDefaults standardUserDefaults]synchronize];


}
else {
    [[NSUserDefaults standardUserDefaults]setObject:@"off" forKey:@"tvpSwitch"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}}

I then put this is any VC viewWillAppear:

-(void)viewWillAppear:(BOOL)animated
{
if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"tvpSwitch"]isEqualToString:@"on"]) 
{
      (sender.isOn=YES);
}
else
{
      (sender.isOn=NO);
}}

It also flags in the viewWillAppear method that reads: "Use of undeclared identifier 'sender'."I usually try using the Reference Guide but I'm having a difficult time identifying where this is going wrong. Any help would be great! Thanks!

Upvotes: 0

Views: 527

Answers (2)

vadian
vadian

Reputation: 285180

In the first code snippet sender is the parameter passed in the IBAction method which is a reference to the UISwitch.

In the other view controllers you need some reference to that UISwitch but if you want only to check that state without being able to change it in the UI, just get it from NSUserDefaults and use it.

By the way there are designated methods of NSUserDefaults for saving a BOOL type.

- (IBAction)tvpSwitch:(UISwitch *)sender {
   [[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:@"tvpSwitch"];
}

BOOL switchState;

-(void)viewWillAppear:(BOOL)animated
{
    switchState = [[NSUserDefaults standardUserDefaults] boolForKey:@"tvpSwitch"];
   // do something with switchState
}

Upvotes: 0

Dante Puglisi
Dante Puglisi

Reputation: 668

Like you have an IBAction there, I suppose you created the UISwitch trough Interface Builder. If that's the case, create an IBOutlet from the UISwitch and then always reference to it.

Upvotes: 0

Related Questions