Objective-C: NSTimer and Countdown

I know that I must understand the Apple documentation for NSTimer, but I do not! I also read a lot of questions about this, but cannot find the one that suits my case. Well here it is:

The user enters the hour and minutes through the text fields. I convert them to integers and display them in "countDownLabel".

  • How can I count down to zero?
  • It would be nice to show the seconds that the user did not import, but I think it will not be easy to show.
  • How can anyone stop this procedure by pressing the UIButton button?

I know that I ask a lot ... I would be very 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; 
+4
source share
2 answers

First you have to calculate your countdown time, in seconds, and put it in the instance variable (ivar)

 NSTimeInterval totalCountdownInterval; 

I think in order to maintain good accuracy (NSTimer shooting can be turned off for 100 ms and errors will add up), you should write down the start date and put it in another ivar:

 NSDate* startDate = [NSDate date]; 

Then you can start the timer at regular (1 second here) intervals repeatedly calling the method on your class

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

And in this method, you check the elapsed time for 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 */ } 
+17
source

This is a big order. But start with baby steps. You need to create a method in your class that, when called (every N seconds), will update the labels you want to update. Then you set up a timer to call this method every N seconds.

There are several timer options that you could use, but for this case, the most straightforward may be NSTimer scheduleTimerWithTimeInterval: target: selector: userInfo: repeat:.

Write your method so that it looks like - (void)timerFireMethod:(NSTimer*)theTimer , and the selector for the timer method is above @selector(timerFireMethod:) .

0
source

All Articles