NSTimer

不错的入门: http://www.cnblogs.com/wujian1360/archive/2011/09/05/2167992.html

    //关闭定时器  
    [myTimer setFireDate:[NSDate distantFuture]];  
    //页面将要进入前台,开启定时器  
    -(void)viewWillAppear:(BOOL)animated  
    {  
        //开启定时器  
        [scrollView.myTimer setFireDate:[NSDate distantPast]];  
    }  
      
    //页面消失,进入后台不显示该页面,关闭定时器  
    -(void)viewDidDisappear:(BOOL)animated  
    {  
        //关闭定时器  
        [scrollView.myTimer setFireDate:[NSDate distantFuture]];  
    }  


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模式中.)


[timer invalidate]; // 这个函数将timer从当前的RunLoop中remove掉,必须在timer安装的线程中调用这个函数。
    [timer fire];// 可以通过fire这个方法去触发timer,即使timer的firing time没有到达  

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


    - (void) handleTimer: (NSTimer *) timer // timer的回调函数  
    {  
        //在这里进行处理  
        NSLog(@"1");  
          
    //    for (int i = 0; i <= 1000000000; )   
    //    {  
    //        i++;  
    //    }   
    }

你可能感兴趣的:(NSTimer)