代码:
RootViewController.h
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController { //定义定时器 NSTimer *timer; } @end
RootViewController.m
-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; //重新开启定时器 [timer setFireDate:[NSDate distantPast]]; } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // 暂时关闭定时器。 [timer setFireDate:[NSDate distantFuture]]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.title=@"定时器的使用"; //当在有定时器的页面时,定时器是启动的。当离开定时器所在的页面时,定时器停止,当在次地进入时,定时器重新启动。 //定时器函数。 timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(loadData) userInfo:nil repeats:YES]; } -(void)loadData { NSLog(@"I Love You!"); }
时间: 2024-10-20 04:34:02