zoukankan      html  css  js  c++  java
  • NSTimer理解

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

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

     

    指定(注册)一个timer RunLoops

     

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

    有以下三种方法:

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

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

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

    1. // 安装timer(注册timer)  
    2.     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 5// 当函数正在调用时,及时间隔时间到了 也会忽略此次调用  
    3.                                              target: self  
    4.                                            selector: @selector(handleTimer:)  
    5.                                            userInfo: nil  
    6.                                             repeats: YES]; // 如果是NO 不重复,则timer在触发了回调函数调用完成之后 会自动释放这个timer,以免timer被再一次的调用,如果是YES,则会重复调用函数,调用完函数之后,会将这个timer加到RunLoop中去,等待下一次的调用,知道用户手动释放timer( [timer invalidate];)。  

     

    1. - (void) handleTimer: (NSTimer *) timer // timer的回调函数  
    2. {  
    3.     //在这里进行处理  
    4.     NSLog(@"1");  
    5.       
    6. //    for (int i = 0; i <= 1000000000; )   
    7. //    {  
    8. //        i++;  
    9. //    }   
    10. }  
    1. //    [timer invalidate]; // 这个函数将timer从当前的RunLoop中remove掉,必须在timer安装的线程中调用这个函数。  
      1. [timer fire];// 可以通过fire这个方法去触发timer,即使t
  • 相关阅读:
    java面向对象类的继承~ 匿名类 ;多态特性;强制类型转换
    Java面向对象~类和对象&方法,类方法
    1036. Escape a Large Maze
    909. Snakes and Ladders
    559. Maximum Depth of N-ary Tree
    987. Vertical Order Traversal of a Binary Tree
    913. Cat and Mouse
    865. Smallest Subtree with all the Deepest Nodes
    882. Reachable Nodes In Subdivided Graph
    864. Shortest Path to Get All Keys
  • 原文地址:https://www.cnblogs.com/leevaboo/p/3101058.html
Copyright © 2011-2022 走看看