5

I'm new to working with timers on the iPhone and would need some support.

I have a method as below that takes the time and update a UILabel in my userinterface. I also have an NSTimer that calls that method once a second (I only show hours and minutes). This works just fine, except for the first second the App is live (as I understand it takes one second before the timer calls the method).

I would like to call my method from viewDidLoad, but how can I supply the right arguments? Or is there a better way of doing this?

// Timer for updating time
[NSTimer scheduledTimerWithTimeInterval:1.0f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil 
                                repeats:YES];   


-(void)updateTime: (NSTimer *) timer {

    currentTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *currentTimeString = [dateFormatter stringFromDate:currentTime];
    [dateFormatter release];

    timeLabel.text =  currentTimeString;
}

Appreciate anything that would point me in the right direction.

sunkehappy
  • 8,970
  • 5
  • 44
  • 65
Structurer
  • 694
  • 1
  • 10
  • 23

2 Answers2

2

In your method, you don't use the timer variable right? So, why just call [self updateTime:nil]. That should work

vodkhang
  • 18,639
  • 11
  • 76
  • 110
  • Yes you are right. Such a simple and neat solution. Tested and is working fine. Thanks! Seems to also be a solution with "fire" that you can trigger the timer event but I have not had the time to test it yet. – Structurer Jun 22 '10 at 10:09
2

One more option ... you can do:

[NSTimer scheduledTimerWithTimeInterval:0.01f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil  
                                repeats:NO];    

[NSTimer scheduledTimerWithTimeInterval:1.0f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil 
                                repeats: YES];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
ohho
  • 50,879
  • 75
  • 256
  • 383