简体   繁体   中英

How do I call a method after a delay without the delay timer going into the next touch?

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!

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.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM