您的位置:首页 > 移动开发 > IOS开发

iOS 计时器三种定时器的用法NSTimer、CADisplayLink、GCD

2017-06-09 12:03 537 查看
原文:http://www.cocoachina.com/ios/20160919/17595.html

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: