Thursday, May 13, 2010

IPad Math: adding a timer

I added a simple timer to my code.  Just a label at the top of my screen which has a custom button behind it.  I then added the following code to start my timer  and to count down.  Note that right now I display 60 for a while (for seconds) instead of 1:00.  I probably need a more advanced time formatting function.


New properties


I added two new properties, one for my timer, and one to track when the timer was started.

NSDate *timerStart;
NSTimer *timer;



New method declarations



I added an action for choosing the button, as well as a  callback for the timer.

- (void) updateTime:(NSTimer*)timer
- (IBAction) startTimer:(id) sender;





Interface builder changes

I added a label and placed a custom button to intercept actions to the label.  I could have actually implemented touches, but this was easier than a gesture controller.  I then hooked my button the callback to start the timer.
Note that the invisible button is currently highlighted.  Setting it to custom causes it to be hidden, but events still occur.
The implementation of the timer start

Toggle the timer.  Check to see if it is running, if it is then reset the label, and release the timer (by setting the property to null which causes it to be released.


- (void) startTimer:(id) sender
{
if (timerStart!=nil)
{
timerStart=nil;
self.timer=nil;
self.timerLabel.text=@"1:00";
}
else {

self.timerStart=[[NSDate alloc]init];
self.timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
}
}



The callback for counting down


Note the use of floor, without using floor it instantly goes down to 59 when the timer starts, and will reach the end early.


NSDate *current=[[NSDate alloc]init];
int timeLeft=60-floor([current timeIntervalSinceDate:timerStart]);
if (timeLeft>0)
{
[self.timerLabel setText:[NSString stringWithFormat:@":%0d",timeLeft]];
}
else {
self.timer=nil;
}

No comments:

Post a Comment