Breakpoint Breakpoint - 5 months ago 42
Objective-C Question

Show time like a digital clock

I am able to display the current time on my iPad application using the code,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];


NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
timeLabel.text = currentTime;


But this gives the time only when the application is loaded. How do i get the time to keep running? Like a digital clock.

Answer

Use this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];

[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES]

Selector method would be like this:

-(void)targetMethod:(id)sender
{
  NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
  timeLabel.text = currentTime;
}