iOS--NSTimer设置定时器的两种方法

时间:2024-04-16 21:08:11
//方法一:
//创建定时器
NSTimer *timer=[NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextCilcked) userInfo:nil repeats:YES];
//利用消息循环来开启定时器
//创建消息循环
NSRunLoop *runLoop =[NSRunLoop currentRunLoop];
//Mode:1: NSDefaultRunLoopMode;
// 2: NSRunLoopCommonModes ;
//将定时器添加到到runLoop
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode]; //方法二:
//创建定时器
NSTimer *timer1 =[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextCilcked) userInfo:nil repeats:YES];
//开启定时器
[timer1 setFireDate:[NSDate distantPast]];
//暂停定时器
[timer setFireDate:[NSDate distantFuture]]; //取消定时器(永久性停止)
[timer invalidate];
//释放计时器
timer = nil; }
-(void)nextCilcked
{ NSLog(@"timer执行中......");
}