ios开发定时器的使用

来源:互联网 发布:mysql yum 安装 编辑:程序博客网 时间:2024/05/12 23:11

一、NSTimer定时器

由于NSTimer定时器是在RunLoop中实现的,而RunLoop中又需要处理许多事情,所以会造成定时不够精准。

1、创建方式一:

@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *label;//由于定时器由系统管理,所以不需要进行进行strong@property (nonatomic, weak)NSTimer *timer;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];        //把定时器添加到当前runloop中,并设置该runloop的运行模式,避免它受runloop的影响    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];}//定时器倒计时- (void)timeChange{    static int i = 5;        if(i == 0){        //处理相关事件,并且释放定时器                [_timer invalidate];                    }    i--;    self.label.text = [NSString stringWithFormat:@"%d", i];}- (IBAction)didClickNext:(id)sender {    //暂停定时器,并未销毁    [_timer setFireDate:[NSDate distantFuture]];}- (IBAction)didClickBegin:(UIButton *)sender {    //继续定时器    [_timer setFireDate:[NSDate distantPast]];    }

2、创建方式二:

@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *label;@property (nonatomic, strong)NSTimer *timer;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];    //此种方式创建的定时器,必须加入的runloop中才会调用定时功能    //并且必须用strong强引用    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];}//定时器倒计时- (void)timeChange{    static int i = 15;        if(i == 0){        //处理相关事件,并且释放定时器                [_timer invalidate];        _timer = nil;    }    i--;    self.label.text = [NSString stringWithFormat:@"%d", i];}

3、创建方式三:

//初始化一个Invocation对象    NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];    [invo setTarget:self];    [invo setSelector:@selector(timeChange)];


扩:ios中直接调用对象的方法有两种方式

[self performSelector: withObject:];

NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];    [invo setTarget:self];    [invo setSelector:@selector(timeChange)];


二、GCD定时器

@interface ViewController ()    //必须把GCD定时器进行强引用,否则不会循环调用方法  @property (nonatomic, strong)dispatch_source_t timer;    @end    @implementation ViewController    - (void)viewDidLoad {      [super viewDidLoad];     
}
- (void)test3 {    __block NSInteger time = 59; //倒计时时间    //1、创建队列,决定了回调任务在哪里执行    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);        //2、创建定时器    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);        //3、设置时间间隔和精度    dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0); //每秒执行        //4、设置回调任务    dispatch_source_set_event_handler(timer, ^{                if(time <= 0){ //倒计时结束,关闭                        dispatch_source_cancel(timer);                        dispatch_async(dispatch_get_main_queue(), ^{                                //设置按钮的样式                [self.openSeconds setTitle:@"重新发送" forState:UIControlStateNormal];                                self.openSeconds.userInteractionEnabled = YES;            });                    }else{                        int seconds = time % 60;            dispatch_async(dispatch_get_main_queue(), ^{                                                //设置label读秒效果                self.timeLabel.text = [NSString stringWithFormat:@"重新发送(%.2d)",seconds];                                [self.openSeconds setTitle:@"已发送" forState:UIControlStateNormal];                // 在这个状态下 用户交互关闭,防止再次点击 button 再次计时                self.openSeconds.userInteractionEnabled = NO;                            });                        time--;        }    });        //5、开启定时器    dispatch_resume(timer);}

三、CADisplayLink