Rav*_*mar 14
你可以创建一个NSTimer()的对象,并在一定的时间间隔内调用一个函数,如下所示:
var updateTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: "callFunction", userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)
这将每15秒调用一次callFunction().
func callFunction(){
print("function called")
}
Run Code Online (Sandbox Code Playgroud)
这是一个带启动和停止功能的简单示例:
private let kTimeoutInSeconds:NSTimeInterval = 60
private var timer: NSTimer?
func startFetching() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(kTimeoutInSeconds,
target:self,
selector:Selector("fetch"),
userInfo:nil,
repeats:true)
}
func stopFetching() {
self.timer!.invalidate()
}
func fetch() {
println("Fetch called!")
}
Run Code Online (Sandbox Code Playgroud)
如果出现unrecognized selector异常,请确保您的类继承自NSObject,否则计时器的选择器将找不到该函数!
| 归档时间: |
|
| 查看次数: |
6907 次 |
| 最近记录: |