How to stop/invalidate NStimer

2019-03-19 18:02发布

问题:

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?

回答1:

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;
}


回答2:

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];
    }


回答3:

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.



回答4:

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];



回答5:

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;

        }