Delayed call with cancellation option?

How to cause a delay, say, I want to call a method (once) after 3 seconds and how to cancel this call if I need?

+5
source share
3 answers

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

+7
source

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

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

The method should look like this:

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

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

Use the invalidate method for NSTimer to cancel it.

+3

.

NSTimer *timer;

.

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

..

[timer invalidate];
+1
source

All Articles