Nizzre
Nizzre

Reputation: 275

iOS: setting default value for UISwitch

I have some issue with default value for my switch. I added a FirstSwitchValue to UsersDefaults and this function works:

- (void)viewDidLoad
{
 [super viewDidLoad];

 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"FirstSwitchValue"]) {
   NSLog(@"Exists");
 }
 else {
   NSLog(@"Not Exists");
 }
}

My switch looks like this:

- (IBAction)FirstSwitch:(id)sender {

 UISwitch *FirstSwitch = (UISwitch *)sender;
 // saving data
 if (FirstSwitch.on == YES) {
   [self setParamWithName:@"tag" withValue:@"1"];
 }
 else {
   [self setParamWithName:@"tag" withValue:@"0"];
 }
}

If I add

[FirstSwitch setOn:YES animated:YES];

in viewDidLoad method I receive error message that I use undeclared identifier FirstSwitch. After adding declaration like this:

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

my FirstSwitch stopped working. Can anyone help me?

Upvotes: 1

Views: 5893

Answers (3)

WolfLink
WolfLink

Reputation: 3317

You have not synthesized your property manually. You have 3 options:

1: Use the autosynthesized name: _FirstSwitch. You then can use this:

[_FirstSwitch setOn:YES animated:YES];

2: Call the getter function. You can use either:

[self.FirstSwitch setOn:YES animated:YES];

or

[[self FirstSwitch] setOn:YES animated:YES];

3: Synthesize the property yourself. First create an instance variable:

//something.h
@interface somethingClass : UIViewController {
    UISwitch *FirstSwitch;
}
@property (weak, nonatomic) IBOutlet UISwitch *FirstSwitch;

Then synthesize it in your .m

//something.m
@synthesize FirstSwitch = _FirstSwitch;

And your code should work as is after that.

I recommend you read Apple's documentation about properties.

Upvotes: 2

npmrtsv
npmrtsv

Reputation: 434

  • First, give right name to your objects, firstSwitch.
  • Second, if you want to use your property, use it like [self.firstSwitch do something].

Hope it helps you.

Upvotes: 0

kumar123
kumar123

Reputation: 889

If you have make property then use as self.FirstSwitch

Upvotes: 0

Related Questions