Chiko
Chiko

Reputation: 606

Getting the current time and keeping it updated - Objective C

I know how to use NSDate to get the time and display it inside UILabel.

i need to display the date + hours and minutes. any idea how can i keep it updated without busy-waiting?

Thanks!

Upvotes: 4

Views: 5715

Answers (4)

Guo Luchuan
Guo Luchuan

Reputation: 4731

As your comments said , if you want when minutes changes you change the label.text

you should do like this :

1st: get the current time:

NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];

and set the label.text = CURRENTHOUR_AND_YOURMINNUTS;

and then refresh the label next minute,like this :

the first , you can check after 60 - nowSeconds [self performSelector:@selector(refreshLabel) withObject:nil afterDelay:(60 - dateComponents.minute)];

- (void)refreshLabel
{
    //refresh the label.text on the main thread
    dispatch_async(dispatch_get_main_queue(),^{      label.text = CURRENT_HOUR_AND_MINUTES;    });
    // check every 60s
    [self performSelector:@selector(refreshLabel) withObject:nil afterDelay:60];
}

It will check every minute , so the effecent is more than answers above.

When refreshLabel invocated , it means the minutes changed

Upvotes: 2

Abhishek Singh
Abhishek Singh

Reputation: 6166

You can use NSTimer , but , given the above methods , the UILabel won't update on touch Events as the main thread will be busy tracking it.You need to add it to mainRunLOOP

    NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabelWithDate) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

-(void)updateLabelWithDate
{
   //Update your Label
}

You can change the time interval(rate at which you want Updation).

Upvotes: -1

Anil Varghese
Anil Varghese

Reputation: 42977

Use NSTimer to update time on the label

- (void)viewDidLoad
 {
  [super viewDidLoad];

   [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
 }



-(void)updateTime
{


NSDate *date= [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute

formatter1.dateFormat = @"hh:mm a";// use any format 

clockLabel.text = [formatter1 stringFromDate:date];

[formatter1 release];


}

Upvotes: 6

lu yuan
lu yuan

Reputation: 7227

You can use the NSTimer to periodically get the current time.

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

- (void)timerFired:(NSTimer*)theTimer{
 //you can update the UILabel here.
}

Upvotes: 1

Related Questions