Tuesday, March 1, 2011

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?

From stackoverflow
  • 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];
    
    Peter Hosey : 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.
  • 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.

    Steph Thirion : Does the method HAVE to look like this? And is there anything needed to do with the NSTimer instance passed?
    Stephen Darlington : 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.
  • You can also use -[NSObject performSelector:awithObject:afterDelay:], and +[NSObject cancelPreviousPerformRequestsWithTarget:selector:object].

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

0 comments:

Post a Comment