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

iOS的定时器用法

2016-03-11 00:00 519 查看
摘要: 介绍iOS中定时器的三种用法

定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法:

1、NSThread

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
[thread start];

- (void)newThread{
@autoreleasepool{
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(requestMessages) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
}
}


2、GCD

首先定义timer:



这里有一点疑惑:timer若作为成员变量(定义放在@interface里面)定时器可以正常使用,但是在方法里面再去定义的定义的话定时器就完全不起作用了,还请知道的原因的小伙伴多多指教:

NSTimeInterval period = 60.0; //设置时间间隔

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

_timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

dispatch_source_set_timer(_timers, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);

dispatch_source_set_event_handler(_timers, ^{
//在这里执行事件
kDLOG(@"定时时间到");
[self requestMessages];
});

dispatch_resume(_timers);


GCD的形式有很多种,下面再列举两种:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
uint64_t interval = (uint64_t)(10.0 * NSEC_PER_SEC);
dispatch_source_set_timer(_timers, start, interval, 0);
// 设置回调
dispatch_source_set_event_handler(_timers, ^{
kDLOG(@"多线程定时时间到");
[self requestMessages];
});
// 启动定时器
dispatch_resume(_timers);


uint64_t interval = 3 * NSEC_PER_SEC;
dispatch_queue_t queue = dispatch_queue_create("my queue", 0);
_timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timers, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);

dispatch_source_set_event_handler(_timers, ^(){
kDLOG(@"定时时间到");
});
dispatch_resume(_timers);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息