A timer sends a message to an object after a certain amount of time passes. Start by declaring a variable for the timer.
1 2 |
var saveTimer = Timer() |
Starting a Timer
Call the scheduledTimer
method to start a timer. The scheduledTimer
method takes the following arguments:
- A time interval for how often the timer fires, specified in seconds.
- Target, which is the object that receives the message from the timer.
- Selector, which is the function the target should run after receiving the message.
- UserInfo, which is optional additional information you can send.
- Repeats, which indicates whether the timer runs once or repeats.
The following code starts a timer to autosave data every 30 seconds:
1 2 3 4 5 6 |
func startTimer() { saveTimer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(self.autosave), userInfo: nil, repeats: true) } |
The function for the selector needs @objc
at the start of the declaration.
1 2 3 4 |
@objc func autosave(timer: Timer) { <p>} |
Stopping a Timer
Call the invalidate
method to stop a timer. The following code stops a timer:
1 2 3 4 |
func stopTimer() { saveTimer.invalidate() } |