一、NSTimer認識
NSTimer其實是將一個監(jiān)聽加入到系統(tǒng)的RunLoop中去糕簿,當系統(tǒng)runloop到如何timer條件的循環(huán)時探入,會調用timer一次,當timer執(zhí)行完冶伞,也就是回調函數(shù)執(zhí)行之后新症,timer會再一次的將自己加入到runloop中去繼續(xù)監(jiān)聽。
一個timer對象在同一時間只能夠被注冊到一個runloop中响禽,盡管在這個runloop中它能夠被添加到多個runloop模式中去徒爹。
二、NSTimer使用
有以下三種初始化方法:
使用scheduledTimerWithTimeInterval: invocation: repeats:或者scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:這兩個類方法創(chuàng)建一個timer并把它指定到一個默認的runloop模式中
使用timerWithTimeInterval: invocation: repeats:或者timerWithTimeInterval: target: selector: userInfo: repeats: 這兩個類方法創(chuàng)建一個timer的對象 (當創(chuàng)建之后芋类,你必須手動的調用NSRunLoop下對應的方法addTimer:forMode:去將它制定到一個runloop模式中)隆嗅。
使用initWithFireDate: interval: target: selector: userInfo: repeats: 方法分配并創(chuàng)建一個NSTimer的實例(當創(chuàng)建之后,你必須手動的調用NSRunLoop下對應的方法addTimer:forMode:去將它制定到一個runloop模式中)侯繁。
[timer?fire];//可以通過fire這個方法去觸發(fā)timer胖喳,即使timer的firing?time沒有到達
注意:不用scheduled方式初始化的,需要手動addTimer: forMode: ?將timer添加到一個runloop中贮竟。而scheduled的初始化方法將以默認mode直接添加到當前的runloop中丽焊。
以下是一個采用scheduled的初始化方法的60秒倒計時定時器的初始化:
_countDownTimer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
將計數(shù)器的repeats設置為YES時,self的引用計數(shù)會加1咕别。因此可能會導致self(即viewController)不能release技健,所以,必須在viewWillAppear的時候惰拱,將計數(shù)器timer停止雌贱,否則可能會導致內存泄露。
停止的方法為:[self.countDownTimer invalidate];
- (void)invalidate是唯一一個可以將計時器從runloop中移出的方法偿短。