Need Help With NSTimer To Make Stopwatch
I want to create a timer that countdowns 60 seconds and updates a UILabel with the time left.
I have this so far, but how do I connect the int to the time left?
-(IBAction)startTimer
{
NSTimer *myTimer开发者_JS百科;
myTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}
- (void)countDown
{
counterInt--;
myLabel.text = [NSString stringWithFormat:@"%i", counterInt];
}
NSTimer is not the way to go for applications that require precise time measurement. The time interval you specify is only a goal and the NSTimer is not guaranteed to fire at precisely that time. It tries to hit the goal you specify but particularly if the processor is handling a lot, NSTimer accuracy deteriorates.
To accurately measure time you need to use NSDate to record the time when you begin and then go ahead and run the NSTimer the way you are but instead of assuming that an exact second has passed, have your function compare the current time with the start time and that will give you an accurate measurement.
You are passing timeInterval
as 60 seconds so it will be triggered every 60 seconds and not every 1 second for 60 seconds. So it should be,
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(countDown:)
userInfo:nil
repeats:YES] retain];
Another thing is that you are not invalidating the alarm after your purpose is done. So check whether the counterInt
value has reached zero and invalidate it. Since there is another benefit to it, make myTimer
an instance variable.
- (void)countDown:(NSTimer *)aTimer {
counterInt--;
myLabel.text = [NSString stringWithFormat:@"%i", counterInt];
if ( counterInt <= 0 ) {
[myTimer invalidate];
[myTimer release];
myTimer = nil;
}
}
Furthermore you are not handling the case where the stop watch has already started. That part should be handled in your interface action method,
-(IBAction)startTimer:(UIButton *)sender
{
if ( myTimer ) {
/* Timer exists so handle that as appropriate */
[myTimer invalidate];
[myTimer release];
myTimer = nil;
[sender setTitle:@"Start" forControlState:UIControlStateNormal];
} else {
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES] retain];
counterInt = 60;
[sender setTitle:@"Stop" forControlState:UIControlStateNormal];
}
}
EDIT
I have edited the answer to change the method to take an NSTimer
instance as a parameter. You will have to update the method definition accordingly. Update the code too.
As such counterInt
is something that you should declare as an instance variable.
Here you go http://www.iphonedevx.com/?p=1522
精彩评论