iOS NSTimer 使用示例:Objective-C 代码详解
以下是一个使用 NSTimer 的 Objective-C 代码示例:
// 创建一个计时器并设置回调方法
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
// 计时器回调方法
- (void)timerFired:(NSTimer *)timer {
// 在这里执行你想要重复执行的代码
NSLog('Timer fired!');
}
// 停止计时器
[timer invalidate];
timer = nil;
在上面的示例中,我们首先使用 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 方法创建了一个每 1 秒触发一次的计时器,并将其与当前对象的 timerFired: 方法关联起来。然后,我们可以在 timerFired: 方法中编写需要重复执行的代码。最后,我们可以使用 invalidate 方法停止计时器的触发,并将其设置为 nil 释放。
原文地址: http://www.cveoy.top/t/topic/hWKM 著作权归作者所有。请勿转载和采集!