NSTimer详解和倒计时的实现

NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统RunLoop到如何timer条件的循环时,会调用timer一次,当timer执行完,也就是回调函数执行之后,timer会再一次的将自己加入到runloop中去继续监听。

  CFRunLoopTimerRef  NSTimer这两个类型是可以互换的, 当我们在传参数的时候,看到CFRunLoopTimerRef可以传NSTimer的参数,增加强制转化来避免编译器的警告信息

 一个timer对象在同一时间只能够被注册到一个runloop中,尽管在这个runloop中它能够被添加到多个runloop中模式中去。

 

创建Timer对象有以下三种方法:

  使用 scheduledTimerWithTimeInterval:invocation:repeats: 或者scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 这两个类方法创建一个timer和时间表并把它指定到一个默认的runloop模式中。

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
                                 invocation:(NSInvocation *)invocation
                                    repeats:(BOOL)repeats
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
                                     target:(id)target
                                   selector:(SEL)aSelector
                                   userInfo:(id)userInfo
                                    repeats:(BOOL)repeats
seconds触发定时器的秒数,如果这个时间是小于等于0,则取0.1,不能为负。invocation调用是使用的定时器。repeats如果是YES,定时器重新安排自己知道失效。

  使用 timerWithTimeInterval:invocation:repeats: 或者 timerWithTimeInterval:target:selector:userInfo:repeats:这两个类方法创建一个timer的对象,不把它知道那个到run loop. (当创建之后,你必须手动的调用NSRunLoop下对应的方法 addTimer:forMode: 去将它制定到一个runloop模式中.)

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds
                        invocation:(NSInvocation *)invocation
                           repeats:(BOOL)repeats
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds
                            target:(id)target
                          selector:(SEL)aSelector
                          userInfo:(id)userInfo
                           repeats:(BOOL)repeats
第一个参数,1.0代表1秒,如果该值<0,系统会默认为0.1 
第二个参数, target:(id)aTarget,表示发送的对象,如self 
第三个参数,selector:(SEL)aSelector方法选择器,在时间间隔内,选择调用一个实例方法 
第四个参数,userInfo:(id)userInfo此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器。 
第五个参数,repeats:(BOOL)yesOrNo当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。 

  使用 initWithFireDate:interval:target:selector:userInfo:repeats: 方法分配并创建一个NSTimer的实例 (当创建之后,你必须手动的调用NSRunLoop下对应的方法 addTimer:forMode: 去将它制定到一个runloop模式中.)

 

[timer fire];// 可以通过fire这个方法去触发timer,即使timerfiring time没有到达 

 

NSTimer   关闭  time  setFireDate:[NSDate  distantFunture]

   开启  [time setFireDate:[NSDate  distanPast]]

 

NSTimer官方类方法不多,就下面这么一点东西,就都搬上来了:

复制代码
@interface NSTimer : NSObject
//初始化,最好用scheduled方式初始化,不然需要手动addTimer:forMode: 将timer添加到一个runloop中。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;

- (void)fire;  //立即触发定时器

- (NSDate *)fireDate;//开始时间
- (void)setFireDate:(NSDate *)date;//设置fireData,其实暂停、开始会用到

- (NSTimeInterval)timeInterval;//延迟时间

- (void)invalidate;//停止并删除
- (BOOL)isValid;//判断是否valid

- (id)userInfo;//通常用nil

@end
复制代码

 在invalidate之前最好先用isValid先判断是否还在线程中:

if ([scrollTimer isValid] == YES) {
        [scrollTimer invalidate];
        scrollTimer = nil;
}

 

定时器暂停与继续的简要方法:

[timer setFireDate:[NSDate date]]; //继续。
[timer setFireDate:[NSDate distantPast]];//开启
[timer setFireDate:[NSDate distantFuture]];//暂停

 

 

使用NSTimer实现倒计时的一个例子:

-(void)viewDidLoad中添加如下代码,每秒出发一次

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];    //使用timer定时,每秒触发一次,然后就是写selector了。
复制代码
- (void)timerFireMethod:(NSTimer*)theTimer
{
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...奥运时间好了
    [endTime setYear:2008];
    [endTime setMonth:8];
    [endTime setDay:8];
    [endTime setHour:8];
    [endTime setMinute:8];
    [endTime setSecond:8];
    
    NSDate *todate = [cal dateFromComponents:endTime]; //把目标时间装载入date
    [endTime release];

    NSDate *today = [NSDate date];    //得到当前时间

    //用来得到具体的时差
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];
    
    NSLog(@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]);
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值