I have a stopwatch that is working just fine on its own, but when I switch back from another view from the tab bar, the stopwatch does some weird things (tapping the back button on the navigation view works fine).
-
The stopwatch label is hidden when the user switches back from the other tab, even though it should be visible when showing the view.
-
If the stopwatch is running when the user taps on the other tab and taps on the stopwatch tab again, the stopwatch goes to -31:-23.-64, and the stop button (which should reset the timer and show the start button) won’t do anything when tapped.
-
If the stopwatch is not running when the user taps on the other tab and taps on the stopwatch tab again, the stopwatch will start normally, but the stop button is not showing when the user taps the start button.
Here is my code:
.h:
@interface ViewController : UIViewController {
IBOutlet UIButton *btnStart;
IBOutlet UIButton *btnStop;
IBOutlet UILabel *lblTimer;
NSTimer *stopWatchTimer;
NSDate *stopDate;
NSDate *startDate;
}
@property (strong, nonatomic) IBOutlet UILabel *lblTimer;
- (IBAction)btnStart:(id)sender;
- (IBAction)btnStop:(id)sender;
.m:
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss.SS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
lblTimer.text = timeString;
}
- (IBAction)buttonStart:(id)sender {
startDate = [NSDate date];
// Create the stop watch timer that fires every 1ms
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/100.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
btnStop.hidden = NO;
btnStart.hidden = YES;
}
- (IBAction)buttonStop:(id)sender {
[self updateTimer];
btnStop.hidden = YES;
btnStart.hidden = NO;
[stopWatchTimer invalidate];
stopWatchTimer = nil;
}
Please let me know what I can do to fix this, or if anything else is needed.
First of all, it looks like startDate is messed up. The
initis being called. It should probably just be[NSDate date].As for the view not appearing… after calculating the date,
timer.textis being set to something. What is timer? Are you sure that shouldn’t betimer.title? And after you do that, you may need to[timer setNeedsDisplay]to make sure the text is updated on the control if that’s what you want.If the text is still messed up, try to update less often. Maybe every tenth second and see if the text behaves better.