How to stop/invalidate NStimer

白昼怎懂夜的黑 提交于 2019-12-04 11:50:54

问题


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;

        }


来源:https://stackoverflow.com/questions/15170518/how-to-stop-invalidate-nstimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!