Xcode Tutorial: How to Make a Clock

Oct 19, 2012

Here is my first tutorial for Xcode and Objective-C - How to make a clock on the iPhone.  It is really simple and can be created many different ways.  The source code is available after the break.

Code:

.h File:


@interface ViewController : UIViewController {
    
    IBOutlet UILabel *lblTime; //Make sure to connect this to the label in the storyboard/xib
    
    NSDate *currentTime;
    NSTimer *updateTimer;
}

.m File:


- (void)viewDidLoad
{
    [self updateTime];
    
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib.
}

//Updates the timer
- (void)updateTime {
    
    // Without this, the timer would never be erased from the code.
    // This would cause a memory overload.
    [updateTimer invalidate]; 
    updateTimer = nil;
    
    currentTime = [NSDate date];
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    [timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
    lblTime.text = [timeFormatter stringFromDate:currentTime];
    
    updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];

}


No comments:

Post a Comment