15.NSTimer

来源:互联网 发布:淘宝黑莓店 编辑:程序博客网 时间:2024/05/17 07:58

  • NSTimer
    • 介绍
    • 初始化
    • 基本函数运用
    • 注意

NSTimer

介绍

  • NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统runloop到如何timer条件的循环时,会调用timer一次,当timer执行完,也就是回调函数执行之后,timer会再一次的将自己加入到runloop中去继续监听。
  • CFRunLoopTimerRef 和 NSTimer这两个类型是可以互换的, 当我们在传参数的时候,看到CFRunLoopTimerRef可以传NSTimer的参数,增加强制转化来避免编译器的警告信息

初始化

    //初始化,最好用scheduled方式初始化,不然需要手动addTimer:forMode: 将timer添加到一个runloop中。    //而scheduled的初始化方法将以默认mode直接添加到当前的runloop中.    //3.0:间隔秒数触发事件    //userInfo:此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器    //repeats:YES为不断循环触发。NO:只触发一次    //方法一    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(action) userInfo:nil repeats:NO];    //方法二三四:必须手动的调用NSRunLoop下对应的方法 addTimer:forMode: 去将它制定到一个runloop模式中    //方法二    NSTimer *tm = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:3.0 target:self selector:@selector(anctiontm) userInfo:nil repeats:YES];    //方法三    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;    //方法四    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

基本函数运用

    //启动定时器    [timer fire];    //取消定时器      [timer invalidate];      //是否在运行    BOOL tmp = [timer isValid];    //重置时间为:[NSDate date]    [timer setFireDate:[NSDate date]];

注意

    注意:将计数器的repeats设置为YES的时候,self的引用计数会加1。因此可能会导致self(即viewController)不能release,所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。    //停止timer的运行,但这个是永久的停止:(注意:停止后,一定要将timer赋空,否则还是没有释放。    //取消定时器      [timer invalidate];      timer = nil;      //要想实现:先停止,然后再某种情况下再次开启运行timer,可以使用下面的方法:    //首先关闭定时器不能使用上面的方法,应该使用下面的方法:    //关闭定时器      [timer setFireDate:[NSDate distantFuture]];      //开启定时器      [timer setFireDate:[NSDate distantPast]];  
0 0