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