iPhone - NSTimer not repeating after fire

前端 未结 8 1811
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 16:14

I am creating and firing a NSTimer with:

ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:sel         


        
相关标签:
8条回答
  • 2021-02-19 16:31

    You can also copy your code inside this block, which inserts the creation of the Timer in the main thread.

    The code will therefore remain:

    dispatch_async(dispatch_get_main_queue(), ^{
      self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                     target:self selector:@selector(handleTimer:) userInfo:nil repeats: YES];
    });
    
    0 讨论(0)
  • 2021-02-19 16:33

    I don't know why but Timer.scheduledTimer method is not working but Timer.init method worked.

    self.timer = Timer.init(timeInterval: 10.0, repeats: true, block: { (timer) in
                print("\n--------------------TIMER FIRED--------------\n")
                self.checkForDownload()
            })
    RunLoop.main.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode)
    
    0 讨论(0)
  • 2021-02-19 16:35

    You could write the same thing in Swift without running in main loops by:

    ncTimer = Timer.scheduledTimer(timeInterval: 1.0, 
                                   target: self, 
                                   selector: #selector(self.handleTimer), 
                                   userInfo: nil, 
                                   repeats: true)
    ncTimer.fire()
    
    0 讨论(0)
  • 2021-02-19 16:42

    Swift timer with closure:

        let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
             // Do whatever
        }
        timer.fire()
    
    0 讨论(0)
  • 2021-02-19 16:44

    Got it

    Adding timer to mainRunLoop made it working

    0 讨论(0)
  • 2021-02-19 16:45

    You can't just assign to the timer that you have put as a property in your header. This should work:

    self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
    target:self selector:@selector(handleTimer:) userInfo:nil repeats: YES];

    Also: The fire method fires the timer, out of cycle. If the timer is non repeating it is invalidated. After the line that says fire, add this:

    
    BOOL timerState = [ncTimer isValid];
    NSLog(@"Timer Validity is: %@", timerState?@"YES":@"NO");
    
    0 讨论(0)
提交回复
热议问题