Objective-C : NSTimer and countdown

半世苍凉 提交于 2019-11-27 02:58:12

问题


I know that I should understand Apple's documentation for NSTimer, but I don't! I have also read a lot of questions about it but can not find one that suites my case. Well here it is:

The user enter hour and minutes through textfields. I convert those to integers and display them in a "countDownLabel".

  1. How can i make the count down to zero?
  2. It would be nice to show the seconds which is something that the user didn't imported but i guess it will not be hard to show.
  3. How could somebody stop this procedure with a press of a UIButton?

I know that i am asking a lot...I would be really grateful if someone could help!

int intHourhs;
intHourhs=([textHours.text intValue]);
int intMinutes;
intMinutes=([textMinutes.text intValue]);
int *intSeconds;
intSeconds=0;

NSString *stringTotalTime=[[NSString alloc] initWithFormat:@"%.2i:%.2i:%.2i",intHourhs,intMinutes,intSeconds]; 
[countDownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:45]];
countDownLabel.text=stringTotalTime;

回答1:


First you should calculate what your countdown time is, in seconds and put it in a instance variable (ivar)

NSTimeInterval totalCountdownInterval;

I think in order to keep good accuracy (NSTimer firing can be off by as much as 100ms and errors will add up) you should record the date at which the countdown started, and put it in another ivar:

NSDate* startDate = [NSDate date];

Then you can have a timer firing at regular (here 1 second) intervals calling a method on your class repeatedly

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCountdown:) userInfo:nil repeats:YES];

And in that method you check the elapsed time against the total countdown time and update the interface

-(void) checkCountdown:(NSTimer*)_timer {

    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];

    NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;

    if (remainingTime <= 0.0) {
        [_timer invalidate];
    }

    /* update the interface by converting remainingTime (which is in seconds)
       to seconds, minutes, hours */

}



回答2:


That's a big order. But start with baby steps. You need to create a method in your class which, when invoked (every N seconds), will update the labels you want updated. Then you arrange for a timer to invoke that method every N seconds.

There are several timer variants you might use, but for this case the most straight-forward is probably NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:.

Write your method to look like - (void)timerFireMethod:(NSTimer*)theTimer and the selector for the timer method above is @selector(timerFireMethod:).



来源:https://stackoverflow.com/questions/7680877/objective-c-nstimer-and-countdown

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