A couple things here:
1 ) if you want a constantly running timer, don't invalidate it each time "updateTime
" is called (and only call scheduledTimerWithTimeInterval:
once... instead of at the end of each time "updateTime
" is called).
2 ) it looks like you have a single label for displaying your time. You should make your timeFormatter
an ivar (instance variable, so it's created and set only once) and then you can set the format via:
timeFormatter.dateFormat = @"HH:mm:ss";
And you should be all set.
Your new updateTime
method could look like this:
- (void)updateTime {
currentTime = [NSDate date];
lblTime.text = [timeFormatter stringFromDate:currentTime];
}
3 ) If you want three different labels, you need to declare IBOutlets for the three labels and have three different date formatters. For example:
@interface YourViewController : UIViewController ()
{
IBOutlet UILabel * hourLabel; // you need to connect these in your XIB/storyboard
IBOutlet UILabel * minuteLabel;
IBOutlet UILabel * secondLabel;
NSDateFormatter * hourFormatter;
NSDateFormatter * minuteFormatter;
NSDateFormatter * secondFormatter;
}
Then, in your "viewDidLoad:
" method, set up your formatters:
hourFormatter = [[NSDateFormatter alloc] init;
hourFormatter.dateFormatter = @"HH";
minuteFormatter = [[NSDateFormatter alloc] init;
minuteFormatter.dateFormatter = @"mm";
secondFormatter = [[NSDateFormatter alloc] init;
secondFormatter.dateFormatter = @"ss";
And finally, in your "updateTime
" method:
- (void)updateTime {
currentTime = [NSDate date];
if(hourFormatter)
{
if(hourLabel)
{
hourLabel.text = [hourFormatter stringFromDate: currentTime];
} else {
NSLog( @"you need to connect your hourLabel outlet in your storyboard or XIB" );
}
} else {
NSLog( @"you need to allocate and init and set hourFormatter");
}
minuteLabel.text = [minuteFormatter stringFromDate: currentTime];
secondLabel.text = [secondFormatter stringFromDate: currentTime];
}