In Swift 3, you can create a Timer . And, if you use targeting on iOS version 10 and above, you can use block-based markup, which simplifies potential strong link loops, for example:
weak var timer: Timer? func startTimer() { timer?.invalidate() // just in case you had existing `Timer`, `invalidate` it before we lose our reference to it timer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in // do something here } } func stopTimer() { timer?.invalidate() } // if appropriate, make sure to stop your timer in `deinit` deinit { stopTimer() }
In Swift 2, you create NSTimer . And if you use Swift 2, you can use the iOS version up to 10.0, in which case you will have to use the older target / selector pattern:
weak var timer: NSTimer? func startTimer() { timer?.invalidate()
Although NSTimer is usually best for completeness, I should note that you can also use a send timer, which is useful for scheduling timers on background threads. When sending timers, since they are block-based, this avoids some strong support loop problems with the old target / <T24> NSTimer model, as long as you use weak links.
So, in Swift 3:
var timer: DispatchSourceTimer? func startTimer() { let queue = DispatchQueue(label: "com.domain.app.timer")
In Swift 2:
var timer: dispatch_source_t? func startTimer() { let queue = dispatch_queue_create("com.domain.app.timer", nil)
For more information, see the โCreating a Timerโ section in the sample send source in the Debugging Files section of the Concurrency Programming Guide.
Rob Sep 20 '14 at 19:51 2014-09-20 19:51
source share