IOS NSTimerr

本文介绍了 iOS 开发中 NSTimer 的三种使用方法:直接指定目标和选择器、通过 NSInvocation 对象调度以及使用代码块执行任务。同时解释了 fire 和 invalidate 方法的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOS NSTimer

有三种简单的使用方式:

第一种:

//NSTimeInterval   间隔时间
//<#(nonnull id)#> 实施目标
//<#(nonnull SEL)#> 需要执行的方法
//repeats:<#(BOOL)#>] 是否重复
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>];

[timer invalidate];//将其设置为无效

第二种:

//初始化一个Invocation对象NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[selfclass] instanceMethodSignatureForSelector:@selector(init)]];

 [invo setTarget:self];  
 [invo setSelector:@selector(myLog)]; 
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> invocation:invo repeats:<#(BOOL)#>];
[timer invalidate];//将其设置为无效

第三种:

//<#(NSTimeInterval)#>  间隔时间
//<#^(NSTimer *timer)inBlock#> 执行代码块
//是否重复
 [NSTimer bk_scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> block:<#^(NSTimer *timer)inBlock#> repeats:<#(BOOL)#>];

注意:NSTimer 中fire 和invalidate的区别;
invalidate
Stops the receiver from ever firing again and requests its removal from its run loop
This method is the only way to remove a timer from an NSRunLoop object

fire
Causes the receiver’s message to be sent to its target
If the timer is non-repeating, it is automatically invalidated after firing

具体比较

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值