• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

iOS NStimer计时器的使用

武飞扬头像
#摩斯先生
帮助5

一. 常用的两种初始化方法:

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);
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfgkgci
系列文章
更多 icon
同类精品
更多 icon
继续加载