How should I go about this?
I have a UISwitch. When the user taps the switch, something amazing happens!
Now, if the user double taps the switch, I haver an amazing crash! Because the first tap was still doing amazing things!
What I’m trying to do is this,
USER TAPS:
1 – toggleOvertimeSwitch is called
2 – Removes target from switch (in order to avoid being called if a double tap happens)
3 – Do amazing things
4 – Add target again
Although there are a few concerns to take care about the Switch position later on, at first glance, this should work. But it doesn’t.
I am removing myself as the target, but it still keeps responding the all the taps! toggleOvertimeSwith is always being called. I don’t understand why.
Can anyone help me figure this out please?
Thank you!
Nuno
Code:
My viewDidLoad implements this,
[self.toggleSwitch addTarget:self
action:@selector(toggleOvertimeSwitch:)
forControlEvents:UIControlEventValueChanged];
And my toggleOvertimeSwitch implements this,
-(void)toggleOvertimeSwitch:(UISwitch *)sender
{
[self.toggleSwitch removeTarget:self
action:@selector(toggleOvertimeSwitch:)
forControlEvents:UIControlEventValueChanged];
// Do something amazing here
[self.toggleSwitch addTarget:self
action:@selector(toggleOvertimeSwitch:)
forControlEvents:UIControlEventValueChanged];
}
If your part mentioning “do something amazing” is executed in the same thread/queue as the rest of your code, it won’t change anything, as every event / use action is handled in the main thread, so from the beginning of your
toggleOvertimeSwitch:to its end, there won’t be any interruption or any other call of this method triggered by any user action before the method itself is finished.If your “amazing thing” code is executed in a separate thread, for example using the GCD
dispatch_asyncfunction, then it is meaningful to disable your switch action, but:enabledproperty of your switch to disable and re-enable it, instead of removing and re-adding the target/action, it would be much more easy!I don’t know if you really use GCD or some threading code or whatever to do your “amazing work”, as you didn’t give much info in your question about that, so I’m just completely guessing, but if you use dispatch_async for example, it would give sthg like this:
PS : Again, if you don’t use any threading nor asynchronous code that gets executed in the background, but use code that executes synchronously in the current thread, then your problem does not exist at all as all your
toggleOvertimeSwitch:method will only be executed in one step without interruption, and the next UI event (touch, etc) will only be processed after all that.