一个简单的定时器(NSTimer)的封装

在项目开发中我们有的时候需要用到计时器,比如登录超时,scrollview的滚动等,那么就让我们自己手动的去创建一个类库吧。

  • 1 首先你需要一个向外提供创建的便捷方法。

  • 1.1 这里考虑两种情况,一种是我创建了定时器马上就要开启,另一种情况 则是我不想马上开始。
  • 1.3 然后你需要知道多久运行一次,
  • 1.4 多久向外面发送一次消息。
  • 1.5 还有尽量的去达到一个低耦合高内聚的这么一个思想,所以我们把消息变成一个block也集成在创建方法中,达到高内聚。
  • 1.6 为了低耦合,我们在方法名之前加上pq_这样子的前缀

于是乎这样子的一个类方法就创建完了

/**
 *  快速创建一个定时器,用type区分要不要一开始就执行
 *
 *  @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 方法的实现

+ (instancetype)pq_createTimerWithType:(PQ_TimerType)type updateInterval:(NSTimeInterval)interval repeatInterval:(NSTimeInterval)repeatInterval update:(TimerUpdateBlock)block{
    PQ_TimerManager * timerManager = [[self alloc]init];
    //多少秒更新一次
    timerManager.timeSumInterval = interval;
    //多少秒执行一次
    timerManager.repeatTime = repeatInterval;
    //保存block
    timerManager.updateBlock = block;
    //判断类型
    if(type == PQ_TIMERTYPE_CREATE_OPEN){
        [timerManager pq_open];
    }
    return timerManager;
}

  • 3 定时器至少需要提供两个最基本的方法,开启和关闭

/**
 *  打开
 */
- (void)pq_open{
    //开启之前先关闭定时器
    [self pq_close];
    //把计数器归零
    self.timeInterval = 0;
    //创建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{
    //如果不是开始 直接返回 并且归零计数器
    if (!self.isStart) {
        return;
    }
    self.timeInterval ++;
    NSLog(@"%f",self.timeInterval);
    if (self.timeInterval == self.timeSumInterval) {
        self.timeInterval = 0;
        self.updateBlock();
    }
}

/**
 *  关闭
 */
- (void)pq_close{
    [self.timer setFireDate:[NSDate distantFuture]];
    self.timer = nil;
}
  • 4到上面基本上一个定时器就封装好啦,现在我们在添加一些方法,让它用起来更简单,如果你有特殊需求也可以继续的丰满它。

/**
 *  把时间设置为零
 */
- (void)pq_updateTimeIntervalToZero{
    self.timeInterval = 0;
}
/**
 *  更新现在的时间
 *
 *  @param interval
 */
- (void)pq_updateTimeInterval:(NSTimeInterval)interval{
    self.timeInterval = interval;
}

/**
 *  开机计时
 */
- (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 结束语

我只是对NSTimer进行的很简单的封装,其中可能有逻辑不是很合理的地方,如果您发现了,麻烦告知。当然了,如果刚好对你有用,也麻烦给个星。
demo地址 https://github.com/codepgq/PQSimpleTimer

posted @ 2016-08-01 09:31  小小酥米  阅读(522)  评论(0编辑  收藏  举报