Search code examples
iosuiswitch

iOS UISwitch Action called twice


I have UISwitch IBAction in my app, which is:

- (IBAction)nearMeSwitchAction:(UISwitch *)sender {

        if(nearMeSwitch.isOn)
            [self getLocation];

        [self myMethod];
}

- (void) getLocation
{
  my code...
 [nearMeSwitch setOn:NO animated:YES];
}

In my getLocation method I've used [nearMeSwitch setOn:NO animated:YES] which calls nearMeSwitchAction again when I click on my switch. Therefore myMethod gets called twice. I dont want that. I don't want to execute nearMeSwitchAction when I turn off my switch from getLocation. Is there other way to accomplish this?


Solution

  • You cannot stop nearMeSwitchAction to get called when you changed UISwitch value, but you can stop your myMethod to getting called. Create one Bool property like isFromGetLocation and if it is true don't call the method.

    - (IBAction)nearMeSwitchAction:(UISwitch *)sender {
    
            if(nearMeSwitch.isOn)
                [self getLocation];
            if(isFromGetLocation)
               //For next time
               isFromGetLocation = NO;
            else
                [self myMethod];
    }
    
    - (void) getLocation
    {
        //my code...
        isFromGetLocation = YES;
        [nearMeSwitch setOn:NO animated:YES];
    }