Objective-C (iOS): タイマーを実行

iOSシミュレータのスクリーンショット 2013.01.03 16.05.00

Objective-C: NSTimerViewController.h

#import <UIKit/UIKit.h>

@interface NSTimerViewController : UIViewController

@end

Objective-C: NSTimerViewController.m

#import "NSTimerViewController.h"

@interface NSTimerViewController ()

@end

@implementation NSTimerViewController

NSTimer *timer_;
UILabel *label_;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [startButton setFrame:CGRectMake(0, 0, 100, 50)];
    [startButton setTitle:@"Timer Start" forState:UIControlStateNormal];
    [startButton addTarget:self action:@selector(startTimer) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startButton];
    
    UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [stopButton setFrame:CGRectMake(110, 0, 100, 50)];
    [stopButton setTitle:@"Timer Stop" forState:UIControlStateNormal];
    [stopButton addTarget:self action:@selector(stopTimer) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 320, 50)];
    [self.view addSubview:label];
    label_ = label;
}

- (void)startTimer
{
    if (timer_ == nil) {
        timer_ = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(fire)
                                                userInfo:nil
                                                 repeats:TRUE];
        
    }
}

- (void)stopTimer
{
    if (timer_ != nil) {
        [timer_ invalidate];
        timer_ = nil;
    }
}

- (void)fire
{
    NSDate *date = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    [format setTimeZone:[NSTimeZone defaultTimeZone]];
    label_.text = [NSString stringWithFormat:@"update: %@", [format stringFromDate:date]];
}

@end