前言
public class NSTimer : NSObject
- 作用
- 在指定的时间执行指定的任务。
- 每隔一段时间执行指定的任务。
1、定时器的创建
2、定时器的启动与关闭
// 启动定时器
timer.fireDate = NSDate.distantFuture()
// 暂停定时器
timer.fireDate = NSDate.distantPast()
// 关闭定时器,永久关闭定时器
timer.invalidate()
3、子线程定时器的创建
在子线程创建定时器时,需要手动开启子线程的运行循环。
dispatch_async(dispatch_get_global_queue(0, 0)) {
// 在子线程创建定时器
/*
scheduled 或 timer 方式创建
*/
let timer:NSTimer = NSTimer(timeInterval: 2.0,
target: self,
selector: #selector(ViewController.updateTimer(_:)),
userInfo: nil,
repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
// 启动子线程的运行循环
/*
这句代码就是一个死循环!如果不停止运行循环,不会执行添加到此句之后的任何代码
*/
CFRunLoopRun()
// 停止子线程运行循环之前,不会执行添加到此处的任何代码
}
var num:Int = 0
func updateTimer(timer:NSTimer) {
num = num + 1
// 满足条件后,停止当前的运行循环
if (num == 8) {
// 停止当前的运行循环
/*
一旦停止了运行循环,后续代码能够执行,执行完毕后,线程被自动销毁
*/
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
4、定时任务
1)performSelector
// 延时调用
/*
1.5 秒后自动调用 self 的 hideHUD 方法
*/
self.performSelector(#selector(NsTimer.hideHUD), withObject: nil, afterDelay: 1.5)
// 取消延时调用
NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(NsTimer.hideHUD), object: nil)
2)GCD
// 多线程
/*
1.5 秒后自动执行 block 里面的代码
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.hud.alpha = 0.0;
}
3)NSTimer
// 定时器
/*
1.5 秒后自动调用 self 的 hideHUD 方法
*/
NSTimer.scheduledTimerWithTimeInterval(1.5,
target: self,
selector: #selector(NsTimer.hideHUD),
userInfo: nil,
repeats: false)
|