Swift
Timer
NSTimer
iOS Development
Swift Programming

How can I use Timer formerly NSTimer in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction to Timer in Swift

In Swift, Timer is a crucial class used for scheduling the execution of a block of code after a timer interval elapses. It was formerly known as NSTimer. Timers can be used for a variety of purposes, such as updating the UI in an app or managing the timing of events.

Timer provides a flexible way to implement recurring or one-time events using the scheduledTimer and timer methods. They execute a block of code after a specified interval or repeatedly based on the specified settings.

Technical Explanation

Timer objects work by triggering a method, selector, or block after a specified duration. To start using timers in your Swift project, import the Foundation framework, as it contains the necessary components to work with timers.

Key Timer Methods in Swift

Swift provides several initializers for Timer. Here, we'll explore two common usage patterns: using scheduled timers and manual timers.

Scheduled Timer

The scheduledTimer methods create a timer that automatically schedules itself on the current run loop in the default mode.

swift
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
    print("This prints every second")
}

Manual Timer

You can create a timer manually and then add it to a run loop with add(_:forMode:).

swift
1let timer = Timer(timeInterval: 1.0, repeats: true) { (timer) in
2    print("Fired manually added timer")
3}
4RunLoop.current.add(timer, forMode: .common)

Invalidating a Timer

A timer can either repeat or run once. When the timer is no longer needed, or before it is destroyed, it should be invalidated to free up resources.

swift
timer.invalidate()

Important Timer Properties

  • timeInterval: Duration between timer firings, in seconds.
  • tolerance: Validity range around the timer firing time, every timer should set this appropriately for energy efficiency.
  • isValid: Boolean property that indicates whether the timer is currently running.

Repeating vs. Non-Repeating Timers

  • Repeating Timers act as a loop and run at specified intervals. To stop them, you must invalidate them manually.
  • Non-Repeating Timers fire exactly once; there is no need to invalidate them.

Using Timers with a Method Selector

One of the classical ways to fire events is using a selector:

swift
1class MyClass {
2    var timer: Timer?
3
4    func startTimer() {
5        timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
6    }
7
8    @objc func timerFired() {
9        print("Selector-based timer fired.")
10    }
11
12    func stopTimer() {
13        timer?.invalidate()
14    }
15}

Memory Management with Timers

Memory management can be a concern with timers, especially if they're retaining self, causing retain cycles. Using weak references prevents this:

swift
1class MyClass {
2    var timer: Timer?
3
4    func startWeakTimer() {
5        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
6            self?.doSomething()
7        }
8    }
9
10    func doSomething() {
11        print("Doing something with weak reference.")
12    }
13}

Summary Table

FeatureDescription
timeIntervalSpecifies the interval between timer invocations.
repeatsIndicates if a timer repeats after firing once.
toleranceAllows flexibility, enhancing power efficiency.
isValidProperty to check if a timer is valid and running.
InvalidationStops the timer and frees associated resources.
Manual vs ScheduledScheduled sets itself, manual needs run loop addition.
Method Selector UsageUse @objc method to handle timer callbacks.
Closure UsageDirectly execute Swift code via closures.

Conclusion

Timers are a powerful and essential tool for managing time-based tasks in iOS development with Swift. Understanding their properties and the potential pitfalls, such as retain cycles, allows developers to accurately schedule tasks without compromising app performance. Always ensure to invalidate timers when they're no longer needed, and use weak references to avoid potential retain cycles. With these best practices, you can effectively manage timers within your Swift applications.


Course illustration
Course illustration

All Rights Reserved.