在如今不少app中,咱们常常会看到轮播图,轮播广告等等,好比淘宝、京东商城app,他们均可以定时循环地播放广告、图片,背后的功臣之一就是今天的主角——定时器 NSTimer。bash
简单地介绍了它的应用场景,接下来,说说这次要分享的技能点:app
###定时开始:oop
我建立一个
HomeViewController
,而后让他成为导航控制器的RootViewController
,在HomeViewController
的viewDidLoad
调用定时器方法,以下代码:学习
#import "HomeViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self regularTime];
}
/*
定时器的常规用法
*/
- (void)regularTime
{
//自动开启
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
- (void)timerAction
{
NSLog(@"定时器:%s",__func__);
}
@end
复制代码
运行结果:每隔一秒就打印一次。 ui
![]()
复制代码
还有另一种方式也能够开启定时器,那就是调用这个方法:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
spa
**注意1:**单独地写这一句代码,默认是不会开启定时器的,让咱们看看苹果官方原文是怎么说的:“
You must add the new timer to a run loop, using addTimer:forMode:. Then, after ti seconds have elapsed, the timer fires, sending the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)
” 也就是说,须要添加到runloop中,手动开启。运行的结果同上。线程
**注意2:**在主线程中,runloop是默认开启,若是是在子线程中开启开启定时器,那么咱们还须要手动开启runloop。运行的结果同上。code
注意3: NSRunLoopCommonModes和NSDefaultRunLoopMode优先级使用场景不一样:通常都是默认模式。cdn
scheduledTimerWithTimeInterval
方法时,此时Timer会被加入到当前线程的RunLoop中,且模式是默认的NSDefaultRunLoopMode
,若是当前线程就是主线程,也就是UI线程时,某些UI事件,好比UIScrollView的拖动操做,会将RunLoop切换成NSEventTrackingRunLoopMode
模式,在这个过程当中,默认的NSDefaultRunLoopMode
模式中注册的事件是不会被执行的,也就是说,此时使用scheduledTimerWithTimeInterval
添加到RunLoop中的Timer就不会执行。NSRunLoopCommonModes
,这个模式等效于NSDefaultRunLoopMode
和NSEventTrackingRunLoopMode
的结合。(参考官方文档) 代码以下所示:- (void)viewDidLoad {
[super viewDidLoad];
//在主线程中开启定时器
[self regularTime];
//在子线程中开启定时器
// [NSThread detachNewThreadWithBlock:^{
// NSLog(@"%@",[NSThread currentThread]);
// [self regularTime];
// }];
}
- (void)regularTime
{
timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//runloop中添加定时器
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//在子线程中启用定时器必须开启runloop
// [[NSRunLoop currentRunLoop] run];
}
- (void)timerAction
{
NSLog(@"定时器:%s",__func__);
}
复制代码
####fire方法blog
简单说说fire方法,fire是火焰的意思,从字面意思能够联想到燃料、加速的意思,that’s right!
[timer fire]
——>就是加速计时的意思,咱们经过好比点击事件,来让定时器人为地加速计时,这个比较简单,这里就很少赘述。
####GCD定时器
GCD定时器,经过建立队列、建立资源来实现定时的功能,以下代码所示: **注意:**若是延迟2秒才开启定时器,那么
dispatch_resume(gcdTimer)
必须写在外面。
#import "HomeViewController.h"
@interface HomeViewController ()
{
NSTimer * timer;
}
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self gcdTimer:1 repeats:YES];
}
- (void)gcdTimer:(int)timerInterVal repeats:(BOOL)repeat
{
//建立队列
dispatch_queue_t queue = dispatch_queue_create("my queue", 0);
//建立资源
dispatch_source_t gcdTimer = dispatch_source_create(&_dispatch_source_type_timer, 0, 0, queue);
dispatch_source_set_timer(gcdTimer,dispatch_time(DISPATCH_TIME_NOW, 0),1*NSEC_PER_SEC,0);
dispatch_source_set_event_handler(gcdTimer, ^{
if (repeat) {
NSLog(@"重复了");
[self timerAction];
} else
{
// [self timerAction];
// //调用这个方法,释放定时器
// dispatch_source_cancel(gcdTimer);
//延迟两秒会出现什么状况呢?
/*
为什么会调用两次?2秒以后再触发定时器后,耽搁了0.001秒去cancel,那定时器已经再次
触发了,因此走了两次,解决的方法就是把cancel写在外面。
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)
(timerInterVal*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self timerAction];
});
dispatch_source_cancel(gcdTimer);
}
});
dispatch_resume(gcdTimer);
}
/*
定时器的常规用法
*/
- (void)regularTime
{
//自动开启
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector
(timerAction) userInfo:nil repeats:YES];
}
- (void)timerAction
{
NSLog(@"定时器:%s",__func__);
}
复制代码
#####定时器循环引用的解决思路
- 循环引用出现的场景: eg:有两个控制器A和B,A 跳转到B中,B开启定时器,可是当我返回A界面时,定时器依然还在走,控制器也并无执行dealloc方法销毁掉。
复制代码
先说简单的解决思路: 苹果官方为了给咱们解决这个循环引用的问题,提供了一个定时器的新的自带方法:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
代码以下:
- (void)regularTime
{
//用苹果自带的方法,使用weakself就能够解决定时器循环引用问题
__weak typeof(self)weakSelf = self;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
[weakSelf timerAction];
}];
}
复制代码
第二种思路:
- (void)regularTime
{
//自动开启
//timer置为nil或者__weak typeof(self)weakself = self也没法解决定时器循环引用问题
__weak typeof(self)weakself = self;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:weakself selector:
@selector(timerAction) userInfo:nil repeats:YES];
}
复制代码
既然如此,那该如何是好? 答案是:经过类扩展,本身改写NSTimer的类方法,在控制器中调用新的类方法,直接show the code:
复制代码
NSTimer+HomeTimer.h中:
#import <Foundation/Foundation.h>
@interface NSTimer (HomeTimer)
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)timerInterval block:(void(^)())block repeats:(BOOL)repeat;
+ (void)timerAction:(NSTimer *)timer;
@end
复制代码
NSTimer+HomeTimer.m中:
#import "NSTimer+HomeTimer.h"
@implementation NSTimer (HomeTimer)
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)timerInterval block:(void(^)())block repeats:(BOOL)repeat
{
return [self timerWithTimeInterval:timerInterval target:self selector:@selector(timerAction:) userInfo:block repeats:YES];
}
+ (void)timerAction:(NSTimer *)timer
{
void (^block)() = [timer userInfo];
if (block) {
block();
}
}
@end
复制代码
类扩展写好以后,在控制器中调用,重写类方法,让定时器对NSTimer类强引用,类是没有内存空间的,就没有循环引用,跟苹果提供的新方法是相似的处理方式,以下代码和运行结果所示:
#import "HomeTimerViewController.h"
#import "NSTimer+HomeTimer.h"
@interface HomeTimerViewController ()
{
NSTimer * timer;
}
@end
@implementation HomeTimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self regularTime];
self.view.backgroundColor = [UIColor greenColor];
}
- (void)regularTime
{
__weak typeof(self)weakSelf = self;
timer = [NSTimer timerWithTimeInterval:1.0f block:^{
[weakSelf timerAction];
} repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)timerAction
{
NSLog(@"定时器:%s",__func__);
}
- (void)dealloc
{
NSLog(@"%s",__func__);
}
@end
复制代码
###定时结束:用时2小时32分钟 ###总结:
我以前在开发app的时候,对定时器更可能是会用的层次,通过此次的深刻学习,对定时器的原理有了更深刻的理解、认识,技术的提高,不少时候都是基础知识的延伸,对原理理解透彻,不少东西就能够触类旁通,所有都通了,但愿对本身和各位同道人有所帮助。