Question

So I have an app that when a user touches a certain object, I kick-off a selector via delay. I am not sure I want or need the delay, but am not sure of best practice, maybe a queue? Anyway, here is what I need, regardless of what I have now.

WHAT I HAVE NOW

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doSomething) object:self];
[self performSelector:@selector(doSomething) withObject:nil afterDelay:2.0];

When the user touches a certain object I need to kick-off a method, but if he/she touches the object again, I want to not call the method.

Use case #1:

  1. User touches object
  2. User does nothing for 2 seconds
  3. Call selector

Use case #2:

  1. User touches object then
  2. User touches object .5 seconds later (so cancel selector call)
  3. User touches object .3 seconds later (so cancel selector call)
  4. User touches object .9 seconds later (so cancel selector call)
  5. User doesn't touch anything for 2 seconds
  6. Call selector

If feel like performSelector and cancelPrevious are hacky. Should I be using some sort of queue and then clearing out the queue every time the user touches again?

Or should I use a timer and just restart the timer each time the user touches it?

No correct solution

OTHER TIPS

I wrote something quick, hopefully it'll help. Every time start is hit the timer resets

@interface ViewController ()
{
    NSTimer *timer;
    NSInteger seconds;
}
@end

- (IBAction)start:(id)sender
{
    seconds = 5;
    [timer invalidate];
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(execute) userInfo:nil repeats:YES];
}

- (void)execute
{
    if(seconds > 0) {
        NSLog(@"seconds: %li", (long)seconds);
        seconds--;
    }
    else {
        NSLog(@"fire");
        [timer invalidate];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top