天天看點

iOS——NSTimer的使用,計時器的簡單建立

NSTimer用到的地方很多,這裡僅以計時器作為例子,裡面的代碼可以應用在很多程式中。

以下是全部的源碼。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UILabel *timerLabel;

@property (nonatomic, assign) int count;

@end

@implementation ViewController

- (IBAction)startBtnClick:(id)sender {  //開始</span>
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(repeatShowTime:) userInfo:@"admin" repeats:YES];
}

- (IBAction)stopBtnClick:(id)sender {  //停止</span>
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.count = 0;
    self.timerLabel.text = @"00:00";
}

- (IBAction)pauseBtnClick:(id)sender {   //暫停</span>
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (IBAction)continueClick:(id)sender {   //繼續</span>
    [self.timer setFireDate:[NSDate date]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)repeatShowTime:(NSTimer *)tempTimer {
    
    self.count++;
    
    self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d",self.count/60,self.count%60];
}

- (void)dealloc {   //銷毀NSTimer</span>
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
           

效果圖如下:

iOS——NSTimer的使用,計時器的簡單建立