多线程创建计时器Timer

(1)计时器, 使用多线程建立,以及释放

  • (void)viewDidLoad{
    [self createTimer];
    }

  • (void)dealloc
    {
    [self deallocTimer];
    }

// 返回之后,停止计时器

  • (void)deallocTimer{
    if (self.myTimer != nil) {
    dispatch_source_cancel(self.myTimer);
    self.myTimer = nil;
    }
    }

  • (void)createTimer{

    __block NSInteger time = 5; //倒计时时间
    self.timeInteger = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    dispatch_source_set_timer(self.myTimer, DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_resume(self.myTimer);

    dispatch_source_set_event_handler(self.myTimer, ^{

      if(time <= 0){ //倒计时结束,关闭
          
          dispatch_source_cancel(self.myTimer);
          
          dispatch_async(dispatch_get_main_queue(), ^{
              self.bottomButton.enabled = YES;
              // 改变底部view的背景颜色
              self.bottomButton.backgroundColor = [UIColor colorWithHexString:@"#FF6868"];
              [self.bottomButton setTitle:@"我已阅读并同意条款" forState:UIControlStateNormal];
              [self.bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
          });
      } else{
          NSLog(@"我已阅读并同意条款(%d秒)", time);
          dispatch_async(dispatch_get_main_queue(), ^{
              [self.bottomButton setTitle:[NSString stringWithFormat:@"我已阅读并同意条款(%d秒)", time] forState:UIControlStateNormal];
              time --;
          });
      }
    

    });
    }

你可能感兴趣的:(多线程创建计时器Timer)