一. 常用的两种初始化方法:
NSTimer类中两种创建对象的类方法,在下面会举例使用
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer));
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
二.如何使用:
(1)第一种创建计时器NSTimer的方法:
[NSTimer scheduledTimerWithTimeInterval:1 repeats:NO block:^(NSTimer * _Nonnull timer) {
//你需要实现的操作在这写
}];
参数说明:
scheduledTimerWithTimeInterval 设置多长时间执行一次,这里是一秒
repeats 是否循环重复执行,属性有NO/YES ; NO就只执行一次,YES的话就每隔1秒执行一次
(2)第二种创建计时器NSTimer的方法:
第二种方式可以利用userInfo:属性来传值
NStimer *timer = [NStimer new];//初始化
NSString *str = [NSString stringWithFormat:@"你想传值的内容+",1];
timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(timerClick) userInfo:str repeats:YES];
-(void)timerClick{
//你需要实现的操作在这写
}
参数说明:
target 添加到的对象,即谁调用
selector 需要调用的方法,timerClick是这里调用的方法
userInfo 可以传需要的值,是一个字符串类型的值
(3)定时器的停止
[timer invalidate];
timer = nil;
将定时器的资源释放掉,定时器所执行的方法体则都全部停止执行完毕.
三、具体实例:
简易的计时器,记录时间
NStimer *timer = [NStimer new];//初始化
int timenum = 0;
//NSString *str = [NSString stringWithFormat:@"你想传值的内容+",1];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
-(void)timerClick{
_timenum++;
nslog(@"%ld",_timenum);
}