在main.storyboard创建如下界面
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *timeLabel; @property (weak, nonatomic) IBOutlet UIButton *startBtn; @property (weak, nonatomic) IBOutlet UIButton *resetBtn; @end
@interface ViewController () { int _seconds;//秒数 dispatch_queue_t _queue;//线程队列 BOOL _isPause;//是否暂停 NSCondition *_condition;//加锁 } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //锁要初始化!!! _condition = [[NSCondition alloc]init]; } #pragma mark-点击 开始/暂停/继续 按钮 - (IBAction)clickStartBtn:(UIButton *)sender { if (_queue==NULL) { //点击开始按钮 _seconds = 0; _isPause = NO; [_startBtn setTitle:@"暂停" forState:UIControlStateNormal]; //禁用重置按钮 _resetBtn.enabled = NO; //开启线程,进行计时 //GCD //创建队列 _queue = dispatch_get_global_queue(0, 0); //开启线程 dispatch_async(_queue, ^{ while (YES) { //加锁 [_condition lock]; //不断的计时 //睡一秒 [NSThread sleepForTimeInterval:0.1]; //判断是否暂停计时 if (_isPause) { //等待 [_condition wait]; } //累加时间 _seconds++; //不断的更新标签上的时间(主线程) dispatch_async(dispatch_get_main_queue(), ^{ _timeLabel.text = [NSString stringWithFormat:@"%02d:%02d",_seconds/60,_seconds%60]; }); //解锁 [_condition unlock]; } }); }else if ([_startBtn.titleLabel.text isEqualToString:@"暂停"]){ //点击暂停按钮 [_startBtn setTitle:@"继续" forState:UIControlStateNormal]; //开启重置按钮 _resetBtn.enabled = YES; //让线程暂时停止计时 _isPause = YES; }else if ([_startBtn.titleLabel.text isEqualToString:@"继续"]){ //点击继续按钮 [_startBtn setTitle:@"暂停" forState:UIControlStateNormal]; //禁用重置按钮 _resetBtn.enabled = NO; //加锁 [_condition lock]; //取消暂停状态 _isPause = NO; //继续计时,发送消息 [_condition signal]; //解锁 [_condition unlock]; } } #pragma mark-点击复位按钮 - (IBAction)clickReSetBtn:(UIButton *)sender { //更新界面 [_startBtn setTitle:@"开始" forState:UIControlStateNormal]; _timeLabel.text = @"00:00"; //更新默认的值 _queue = NULL; }
@end;