0

What I mean is, I am writing an app that, after the user touches the screen, performs some actions in the touchesBegan method. Then after 2.5 seconds it calls another method. The problem I'm having is that I don't think the timer stops and starts over after I release and tap and touch again.

Here's the code I have written:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [UIImageView beginAnimations:nil context:NULL];
    _stan.frame = CGRectMake(20, 70, 111, 124);
    [UIImageView setAnimationDuration:.75];
    [UIImageView commitAnimations];

    [self performSelector:@selector(endJump) withObject:nil afterDelay:2.5];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self endJump];
}

-(void)endJump {
    [UIImageView beginAnimations:nil context:NULL];
    _stan.frame = CGRectMake(20, 110, 111, 124);
    [UIImageView setAnimationDuration:.75];
    [UIImageView commitAnimations];
}

What I'd like it to do is have my character jump, then after 2.5 seconds, he falls and lands on the ground again. What's happening is that it works the first time, but in some subsequent touches and holds, he falls early, and not after 2.5 seconds.

Thanks for any help!

2 Answers2

0

performSelector: does not cancel the future request just because you have already called the method. While you can cancel performSelector:, you would be better served by using an NSTimer instance, set to be non repeating, created when your touches start and invalidate (cancelled) it when your touches end.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • That did it! Thank you very much. I really should've come up with this, but it's late and I've been at this a bit too long. Anyway, it worked perfectly! Thanks again! – hentercenter Feb 02 '14 at 09:06
  • @Wain no need of creating timer.check my answer – santhu Feb 02 '14 at 09:34
  • @santhu, I didn't say required, I said better. The timer is dedicated and appropriate to the task at hand. – Wain Feb 02 '14 at 09:46
0

You don't need to create NSTimer for this as Wain suggested in his answer.

Instead, you call below function,

[NSObject cancelPreviousPerformRequestsWithTarget:self];

So, your final method will be ->

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [UIImageView beginAnimations:nil context:NULL];
    _stan.frame = CGRectMake(20, 70, 111, 124);
    [UIImageView setAnimationDuration:.75];
    [UIImageView commitAnimations];

    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(endJump) withObject:nil afterDelay:2.5];
}
santhu
  • 4,796
  • 1
  • 21
  • 29