Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to observer variable value changes over time in xcode

I'm currently learning ios developement using swift and I was just wondering if there is a way in xcode to

1) set a breakpoint on a variable whenever the value of the variable changes

OR

2) somehow track the change to variable value over time

like image 714
Thor Avatar asked Aug 15 '16 07:08

Thor


2 Answers

Method with Swift didSet and willSet

You can use the print in the console:

class Observable {
    static var someProperty: String? {
        willSet {
            print("Some property will be set.")
        }
        didSet {
            print("Some property has been set.")
        }
    }
}

Method with watchpoints

Watchpoints are a tool you can use to monitor the value of a variable or memory address for changes and trigger a pause in the debugger when changes happen. They can be very helpful in identifying problems with the state of your program that you might not know precisely how to track down.

You can find a great guide here

like image 65
Marco Santarossa Avatar answered Nov 06 '22 07:11

Marco Santarossa


I think you should learn about willSet and didSet concepts.

Swift has a simple and classy solution called property observers, and it lets you execute code whenever a property has changed. To make them work, you need to declare your data type explicitly, then use either didSet to execute code when a property has just been set, or willSet to execute code before a property has been set.

Update the value whenever the value was changed. So, change property to this:

 var score: Int = 0 {
  didSet {
      scoreLabel.text = "Score: \(score)"
  }  
}

There is already a good question and answers which expalin this concept.

What is the purpose of willSet and didSet in Swift?

like image 37
Chathuranga Silva Avatar answered Nov 06 '22 08:11

Chathuranga Silva