views:

514

answers:

3

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?

+1  A: 

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];
adam
Don't forget to retain the timer when you set it up and release it after you invalidate it. Relying on the run loop to retain it for you is bad form and risks breakage if Apple ever changes the implementation.
Peter Hosey
+2  A: 

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.

Stephen Darlington
Does the method HAVE to look like this? And is there anything needed to do with the NSTimer instance passed?
Steph Thirion
I think I'm right in saying that the method does need to look like that. The userInfo parameter is used to pass in extra data. It's access as [theTimer userInfo] in your method.
Stephen Darlington
+4  A: 

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

Ben Gottlieb
+cancelPreviousPerformRequestsWithTarget:selector:object: is a class method (+), not an instance method (-). That's why it takes the target (instance) as one of its arguments.
Peter Hosey
Oops, you're right, thanks for the catch!
Ben Gottlieb
This one is much easier to use than NSTimer. Or am I missing something?
Steph Thirion
It is much easier, but it’s also less flexible.
Ahruman