9

I am using

 [NSTimer scheduledTimerWithTimeInterval:0.1f
                                  target:self
                                selector:@selector(update)
                                userInfo:nil
                                 repeats:YES];

I want to stop calling this timer one.

viewDidDisappear

How can i do that? invalidate?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
Shishir.bobby
  • 10,994
  • 21
  • 71
  • 100

5 Answers5

27

Declare NSTimer *myTimer in .h file.

Assign instance as tom said like this

myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f
                                     target:self
                                   selector:@selector(update)
                                   userInfo:nil
                                    repeats:YES];

Stop and Invalidate using this

- (void) viewDidDisappear:(BOOL)animated
{
    [myTimer invalidate];
    myTimer = nil;
}
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
5

Try this

viewController .h

 NSTimer *timer;

viewcontroller.m

  timer = [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(pollTime)
                                       userInfo:nil
                                        repeats:YES];


  - (void) viewDidDisappear:(BOOL)animated 
    {
      [super viewDidDisappear:animated];
      [timer invalidate];
    }
Ravindhiran
  • 5,304
  • 9
  • 50
  • 82
1

Yes, you would use the - (void)invalidate instance method of NSTimer.

Of course, to do that, you would have to save the NSTimer instance returned from [NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] into an ivar or property of your view controller, so you can access it in viewDidDisappear.

tom
  • 18,953
  • 4
  • 35
  • 35
1

invalidate Method of NSTimer is use for stop timer

- (void) viewDidDisappear:(BOOL)animated 
{
        [super viewDidDisappear:animated];
        [self.timer invalidate];
        self.timer = nil;
}

If you are not ARC then don't forget [self.timer release];

iPatel
  • 46,010
  • 16
  • 115
  • 137
1

For stopping or invalidating NSTimer first you have to create instance for NSTimer in Globally.

 Timer=[NSTimer scheduledTimerWithTimeInterval:0.1f
                                  target:self
                                selector:@selector(update)
                                userInfo:nil
                                 repeats:YES];

after that try like this,

if (Timer != nil) {

            [Timer invalidate];
            Timer = nil;

        }
Balu
  • 8,470
  • 2
  • 24
  • 41