引言

定时器:A timer waits until a certain time interval has elapsed and then fires, sending a specified message to a target object.
翻译如下:在固定的时间间隔被触发,然后给指定目标发送消息。总结为三要素吧:时间间隔、被触发、发送消息(执行方法)

按照官方的描述,我们也确实是这么用的;但是里面有很多细节,你是否了解呢?

  • 它会被添加到runloop,否则不会运行,当然添加的runloop不存在也不会运行;

  • 还要指定添加到的runloop的哪个模式,而且还可以指定添加到runloop的多个模式,模式不对也是不会运行的

  • runloop会对timer有强引用,timer会对目标对象进行强引用(是否隐约的感觉到坑了。。。)

  • timer的执行时间并不准确,系统繁忙的话,还会被跳过去

  • invalidate调用后,timer停止运行后,就一定能从runloop中消除吗,资源????

呵呵。。。下面会解决这些问题

定时器的一般用法

控制器中添加定时器,例如:

- (void)viewDidLoad {    NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(timerFire) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];    self.timer = timer;
}

- (void)timerFire {    NSLog(@"timer fire");
}

上面的代码就是我们使用定时器最常用的方式,可以总结为2个步骤:创建,添加到runloop

系统提供了8个创建方法,6个类创建方法,2个实例初始化方法。

  • 有三个方法直接将timer添加到了

    网友评论