不错的入门: http://www.cnblogs.com/wujian1360/archive/2011/09/05/2167992.html
1 //关闭定时器 2 [myTimer setFireDate:[NSDate distantFuture]]; 3 4//页面将要进入前台,开启定时器 5 -(void)viewWillAppear:(BOOL)animated 6 { 7 //开启定时器 8 [scrollView.myTimer setFireDate:[NSDate distantPast]]; 9 } 10 11 //页面消失,进入后台不显示该页面,关闭定时器 12 -(void)viewDidDisappear:(BOOL)animated 13 { 14 //关闭定时器 15 [scrollView.myTimer setFireDate:[NSDate distantFuture]]; 16 }
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 invalidate]; // 这个函数将timer从当前的RunLoop中remove掉,必须在timer安装的线程中调用这个函数。 2 [timer fire];// 可以通过fire这个方法去触发timer,即使timer的firing time没有到达 3 4(注册timer) 5 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 5// 当函数正在调用时,及时间隔时间到了 也会忽略此次调用 6 target: self 7 selector: @selector(handleTimer:) 8 userInfo: nil 9 repeats: YES]; // 如果是NO 不重复,则timer在触发了回调函数调用完成之后 会自动释放这个timer,以免timer被再一次的调用,如果是YES,则会重复调用函数,调用完函数之后,会将这个timer加到RunLoop中去,等待下一次的调用,知道用户手动释放timer( [timer invalidate];)。 10 11 12 - (void) handleTimer: (NSTimer *) timer // timer的回调函数 13 { 14 //在这里进行处理 15 NSLog(@"1"); 16 17 // for (int i = 0; i <= 1000000000; ) 18 // { 19 // i++; 20 // } 21 }