iOS 计时器三种定时器的用法NSTimer、CADisplayLink、GCD
2017-06-09 12:03
537 查看
原文:http://www.cocoachina.com/ios/20160919/17595.html
DEMO链接🔗
一、三种计时器
二、全局倒计时
一、三种计时器
View Code
DEMO链接🔗
一、三种计时器
二、全局倒计时
一、三种计时器
#import "GlobalTimer.h" #import "AppDelegate.h" @implementation GlobalTimer //倒计时 -(void)timerStarWithTimeInt:(int)times{ _countDown = times; _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes]; //添加通知。进入后台 前台的 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BGAction) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(FGAction) name:UIApplicationWillEnterForegroundNotification object:nil]; } //倒计时事件 -(void)timerAction:(NSTimer*)timer{ if (_countDown == 0) { [self timerStop]; }else{ _countDown -=1; } } //进入前台事件 -(void)FGAction{ NSDate * now = [NSDate date]; int interval = (int)ceil([now timeIntervalSinceDate:_beforeDate]);//与上次时间的时间差 int val = _countDown - interval; if (val>1) { _countDown -= interval; }else{ _countDown = 1; } } //进入后台事件 -(void)BGAction{ _beforeDate = [NSDate date];//获取当前时间 } -(void)timerStop{ [_timer invalidate]; _timer = nil; //移除通知 [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; } //循环次数计时器 -(void)timerStarWithcountEveryTimeInt:(int)count timesOfTotalInt:(int)times{ // _countDown = times; // _timer = [NSTimer scheduledTimerWithTimeInterval:count target:timer selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>] // } @end
View Code
相关文章推荐
- iOS 中三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS 中三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS 中三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS - 中三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS - 中三种定时器的用法NSTimer、CADisplayLink、GCD
- iOS 中三种定时器的用法NSTimer、CADisplayLink、GCD
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- iOS经典讲解之NSTimer、CADisplayLink、GCD三种定时器的使用
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- NSTimer、CADisplayLink、GCD 三种定时器的用法 —— 昉
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- iOS 定时器 NSTimer、CADisplayLink、GCD3种方式的实现
- NSTimer、CADisplayLink 和 GCD 定时器用法
- iOS:三种常见计时器(NSTimer、CADisplayLink、dispatch_source_t)的使用
- IOS的三种定时器 GCD CADisplayLink NSTimer
- iOS开发之UITableView中计时器的几种实现方式(NSTimer、DispatchSource、CADisplayLink)