Created
June 24, 2022 13:01
-
-
Save robertmryan/f769086620f10d9319f67e282429e8d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
@IBOutlet var label: UILabel! | |
private weak var timer: Timer? | |
override func viewDidAppear(_ animated: Bool) { | |
super.viewDidAppear(animated) | |
startTimer() | |
} | |
override func viewDidDisappear(_ animated: Bool) { | |
super.viewDidDisappear(animated) | |
stopTimer() | |
} | |
func startTimer() { | |
stopTimer() // stop previous timer, if any | |
var counter = 0 | |
timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in | |
counter += 1 | |
guard let self = self, counter <= 10 else { | |
timer.invalidate() | |
return | |
} | |
let string = String(counter) // was Int.random(in: 1...10), but wanted to see counter progress | |
print(string) | |
self.label.text = string | |
} | |
} | |
func stopTimer() { | |
timer?.invalidate() | |
} | |
} |
Good sample, thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A few observations on the above:
viewDidAppear
, you’d want to stop it inviewDidDisappear
.weak
property for theTimer
instance. Timers are managed by the runloop on which they run, so the view controller only needs aweak
reference. That way, then the timer is invalidated, the run loop will release it, and our reference to the timer will becomenil
.scheduledTimer
, I was conscientious about avoiding strong reference cycle, using[weak self]
capture list. This is another defensive programming technique, which ensures that the timer doesn’t keep a strong reference to the view controller. In this simple case, it technically isn’t necessary (viewDidDisappear
should be sufficient), but it’s a good habit.