定时器的设置

时间:2022-01-05 23:32:28

//设置定时器

- (void)setMyTimer

{

    _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(getDeviceWords) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];//这段代码解决了定时器早scrollView上卡顿的问题。

}

//开启计时器

- (void)startTimer

{

    //开启定时器

    [_timer setFireDate:[NSDate distantPast]];

}

//停止计时器

- (void)stopTimer

{

    [_timer invalidate];

    _timer = nil;

}

//暂停计时器

- (void)pauseTimer

{

    [_timer setFireDate:[NSDate distantFuture]];

}


 

    

    //注册程序进入前台通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (startTimer1) name: UIApplicationWillEnterForegroundNotification object:nil];

    

    //注册程序进入后台通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (pauseTimer1) name: UIApplicationDidEnterBackgroundNotification object:nil];



- (void)dealloc

{

    //销毁计时器

    [self.homePageView stopTimer];

    //解除程序进入前台通知

    [[NSNotificationCenter defaultCenter] removeObserver:self name: UIApplicationWillEnterForegroundNotification object:nil];

    

    //解除程序进入后台通知

    [[NSNotificationCenter defaultCenter] removeObserver:self name: UIApplicationDidEnterBackgroundNotification object:nil];

    

}