NSTimer doesn't stop with invalidate

后端 未结 2 755
予麋鹿
予麋鹿 2020-12-19 10:25

I add timer like this

tim=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeatTim) userInfo:nil repeats:YES];
[[NSRunLoop mainRun         


        
相关标签:
2条回答
  • 2020-12-19 10:46

    Read documentation for NSTimer:

    There are three ways to create a timer:

    1. Use the scheduledTimerWithTimeInterval:invocation:repeats: or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer and schedule it on the current run loop in the default mode.

    2. Use the timerWithTimeInterval:invocation:repeats: or timerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

    3. Allocate the timer and initialize it using the initWithFireDate:interval:target:selector:userInfo:repeats: method. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

    You are using method which already adds it to mainLoop from 1. - you need to remove this line or create a timer with 2. approach and leave manual adding.

    Also remember that you must send invalidate message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

    0 讨论(0)
  • 2020-12-19 10:56

    You have more than one timer running . Try this:

    -(void)startTimer{
        [self.myTimer invalidate]; // kill old timer
        self.myTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
    }
    
    -(void)stopTimer{
        [self.myTimer invalidate];  
        self.myTimer=nil; //set pointer to nil 
    }
    
    0 讨论(0)
提交回复
热议问题