1、声明
NSTimer *timer;
2、定义
timer = [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(updateValue)userInfo:nilrepeats:YES];
以下是调用函数
-(void)updateValue
{
NSLog(@"Hello Timer ");
}
3、打开定时器
-(void)viewWillAppear:(BOOL)animated
{
//开起定时器
[timer setFireDate:[NSDatedistantPast]];
}
4、关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
//关闭定时器
[timer setFireDate:[NSDatedistantFuture]];
}
以下是另外一种GCD timer方法:
1、声明
dispatch_source_t _timer;
2、定义 使用
__weakid weakSelf =self;
double delayInSecond = 0.25;
_timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,dispatch_get_main_queue());
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), (unsigned)(delayInSecond *NSEC_PER_SEC), 0);
dispatch_source_set_event_handler(_timer, ^{[weakSelfupdateValues];});
//开启
dispatch_resume(_timer);
-(void)updateValues
{
NSLog(@"Hello Timer ");
}
3、释放
dispatch_source_cancel(_timer);
dispatch_release(_timer);