Reputation: 9423
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
Reputation: 85532
You can also use -[NSObject performSelector:awithObject:afterDelay:]
, and +[NSObject cancelPreviousPerformRequestsWithTarget:selector:object]
.
Upvotes: 7
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
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