JustANoob
JustANoob

Reputation: 65

Alternatives to using Timers in swift

Just a general question. My project utilizes a ten different swift timers in order to make changes to the UI based on the user's selected settings. The settings are saved to keys and the timers are used to read every second. This works, the problem is that it results in my app using 34% cpu, high energy and 20 % overhead. I was wondering if there are any alternative ways to checking if a user has made any changes to the app's setting and updating the various view controllers as a result.

Upvotes: 0

Views: 1174

Answers (2)

Code Different
Code Different

Reputation: 93191

  1. Create a Settings class/struct using the singleton pattern which provide all the settings of your app.

  2. In Settings, use didSet to update your data store (user defaults / Core Data / cloud storage) when the property change.

  3. If you want the changes to be immediately reflected in the GUI, use Key Value Observing for the view controller.

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54785

Calling functions periodically just to check if some variables changed is really bad practice.

You have several methods to achieve automatic UI updates. One of these methods is describe below.

Swift has property observers, which are called automatically by the system when a certain property/variable changes. All you need to do is set up property observers for each property you use to feed data to the UI and update the UI from inside the property observers.

Say you have variable a, which you use to store data for labelA to display. Below is a Playground example that has been tested and works.

class MyViewController: UIViewController {
    var label:UILabel = UILabel(frame: CGRect(x: 20, y: 20, width: 100, height: 30))

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = a
        label.textColor = .black
        self.view.addSubview(label)
        view.backgroundColor = .white
    }

    var a = "first" {
        didSet {
            label.text = a
        }
    }
}

let myVC = MyViewController()
PlaygroundPage.current.liveView = myVC
sleep(10)
myVC.a = "new value"

You can see that the text on the label changes automatically if you change the value of variable a.

Upvotes: 1

Related Questions