(NSTimer) creating a Timer Countdown

吃可爱长大的小学妹 提交于 2019-12-01 05:24:32

Several things are wrong with your code:

  • You are passing a wrong parameter for the time interval - negative numbers are interpreted as the 0.1 ms
  • You are calling the wrong overload - you are expected to pass an invocation object, yet you are passing a NULL
  • You put the code that you want executed on timer together with timer initialization - the code that needs to be executed on timer should go into a separate method.

You should call the overload that takes a selector, and pass 1 for the interval, rather than -1.

Declare NSTimer *timer and int remainingCounts, then add

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

to the place where you want to start the countdown. Then add the countDown method itself:

-(void)countDown {
    if (--remainingCounts == 0) {
        [timer invalidate];
    }
}

Try this

- (void)startCountdown
{
    _counter = 60;

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

- (void)countdownTimer:(NSTimer *)timer
{
    _counter--;
    if (_counter <= 0) { 
        [timer invalidate];
        //  Here the counter is 0 and you can take call another method to take action
        [self handleCountdownFinished];
   }
}

From the question you posed.you can achieve that by invoking a function for every 1 sec and handle the decrement logic in that.

Snippet:-

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1.0
                      target: self
                      selector:@selector(onTick:)
                      userInfo: nil repeats:YES];
(void)onTick
{
   //do what ever you want
   NSLog(@"i am called for every 1 sec");
//invalidate after 60 sec [timer invalidate];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!