在項(xiàng)目開發(fā)中我們有的時候需要用到計時器,比如登錄超時,scrollview的滾動等,那么就讓我們自己手動的去創(chuàng)建一個類庫吧。
-
1 首先你需要一個向外提供創(chuàng)建的便捷方法。
- 1.1 這里考慮兩種情況,一種是我創(chuàng)建了定時器馬上就要開啟,另一種情況 則是我不想馬上開始。
- 1.3 然后你需要知道多久運(yùn)行一次,
- 1.4 多久向外面發(fā)送一次消息。
- 1.5 還有盡量的去達(dá)到一個低耦合高內(nèi)聚的這么一個思想,所以我們把消息變成一個block也集成在創(chuàng)建方法中,達(dá)到高內(nèi)聚。
- 1.6 為了低耦合,我們在方法名之前加上pq_這樣子的前綴
于是乎這樣子的一個類方法就創(chuàng)建完了
/**
* 快速創(chuàng)建一個定時器,用type區(qū)分要不要一開始就執(zhí)行
*
* @param type
* @param interval
* @param repeatInterval
* @param block
*
* @return
*/
+ (instancetype)pq_createTimerWithType:(PQ_TimerType)type updateInterval:(NSTimeInterval)interval repeatInterval:(NSTimeInterval)repeatInterval update:(TimerUpdateBlock)block
-
2 方法的實(shí)現(xiàn)
+ (instancetype)pq_createTimerWithType:(PQ_TimerType)type updateInterval:(NSTimeInterval)interval repeatInterval:(NSTimeInterval)repeatInterval update:(TimerUpdateBlock)block{
PQ_TimerManager * timerManager = [[self alloc]init];
//多少秒更新一次
timerManager.timeSumInterval = interval;
//多少秒執(zhí)行一次
timerManager.repeatTime = repeatInterval;
//保存block
timerManager.updateBlock = block;
//判斷類型
if(type == PQ_TIMERTYPE_CREATE_OPEN){
[timerManager pq_open];
}
return timerManager;
}
-
3 定時器至少需要提供兩個最基本的方法,開啟和關(guān)閉
/**
* 打開
*/
- (void)pq_open{
//開啟之前先關(guān)閉定時器
[self pq_close];
//把計數(shù)器歸零
self.timeInterval = 0;
//創(chuàng)建timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:self.repeatTime target:self selector:@selector(pq_timeUpdate) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
self.isStart = YES;
}
//更新時間
- (void)pq_timeUpdate{
//如果不是開始 直接返回 并且歸零計數(shù)器
if (!self.isStart) {
return;
}
self.timeInterval ++;
NSLog(@"%f",self.timeInterval);
if (self.timeInterval == self.timeSumInterval) {
self.timeInterval = 0;
self.updateBlock();
}
}
/**
* 關(guān)閉
*/
- (void)pq_close{
[self.timer setFireDate:[NSDate distantFuture]];
self.timer = nil;
}
-
4到上面基本上一個定時器就封裝好啦,現(xiàn)在我們在添加一些方法,讓它用起來更簡單,如果你有特殊需求也可以繼續(xù)的豐滿它。
/**
* 把時間設(shè)置為零
*/
- (void)pq_updateTimeIntervalToZero{
self.timeInterval = 0;
}
/**
* 更新現(xiàn)在的時間
*
* @param interval
*/
- (void)pq_updateTimeInterval:(NSTimeInterval)interval{
self.timeInterval = interval;
}
/**
* 開機(jī)計時
*/
- (void)pq_start{
self.isStart = YES;
}
/**
* 暫停計時
*/
- (void)pq_pause{
self.isStart = NO;
}
/**
* 開始計時器
*/
- (void)pq_distantPast{
[self.timer setFireDate:[NSDate distantPast]];
}
/**
* 暫停計時器
*/
- (void)pq_distantFuture{
[self.timer setFireDate:[NSDate distantFuture]];
}
-
5 使用
self.timerManager = [PQ_TimerManager pq_createTimerWithType:PQ_TIMERTYPE_CREATE_OPEN updateInterval:3 repeatInterval:1 update:^{
//這里處理事件、UI
}];
-
6 結(jié)束語
我只是對NSTimer進(jìn)行的很簡單的封裝,其中可能有邏輯不是很合理的地方,如果您發(fā)現(xiàn)了,麻煩告知。當(dāng)然了,如果剛好對你有用,也麻煩給個星。
demo地址 https://github.com/codepgq/PQSimpleTimer