Steph Thirion
Steph Thirion

Reputation: 9423

Delayed call, with possibility of cancelation?

How do I trigger a delay, let's say I want to call a method (once) in 3 seconds from now, and how do I cancel that call if I need to?

Upvotes: 5

Views: 2437

Answers (3)

Ben Gottlieb
Ben Gottlieb

Reputation: 85532

You can also use -[NSObject performSelector:awithObject:afterDelay:], and +[NSObject cancelPreviousPerformRequestsWithTarget:selector:object].

Upvotes: 7

Stephen Darlington
Stephen Darlington

Reputation: 52565

Use NSTimer. Use this to set up a call to method in three seconds time. It will only be called once:

   [NSTimer scheduledTimerWithTimeInterval: 3
                                    target: self
                                  selector: @selector(method:)
                                  userInfo: nil
                                   repeats: NO];

method needs to look like this:

- (void) method: (NSTimer*) theTimer;

You can pass parameters into the method using userInfo (set to nil in the above example). It can be accessed in the method as [theTimer userInfo].

Use the invalidate method on NSTimer to cancel it.

Upvotes: 3

adam
adam

Reputation: 22587

in your header..

NSTimer *timer;

when you want to setup..

timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO];

when you want to cancel..

[timer invalidate];

Upvotes: 1

Related Questions