20

Say I have a variable, self.position, how do I get Xcode to break whenever it changes its value (a number of methods could change it).

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

4 Answers4

28

For conditional breaking:

  1. Cmd+option click the breakpoint
  2. Add a break condition like so:

enter image description here

For breaking on every occasion the value has changed:

  1. Implement trivial setter (and getter for the sake of clean code).
  2. Add breakpoint to setter.

If you want to see who invoked the setter - just look at the next line in the stack trace (viewDidLoad in my example):

enter image description here

Update:

Adding a watchpoint

  1. Break anywhere so that the (lldb) prompt shows up in the console
  2. Type in watchpoint set variable _position (replace _position with an iVar you want to watch)
  3. Make a note of the assigned watchpoint number to your newly created watchpoint.
  4. Modify the watchpoint for conditional breaking: watchpoint modify -c "_position < 0.5" 1 where the expression in quotes is the condition and the number at the end is the watchpoint number you noted in #3.
  5. Continue running. You'll break whenever the value matches the condition and you'll be able to inspect the stack frame to understand where the call came from.
Stavash
  • 14,244
  • 5
  • 52
  • 80
  • 1
    There are other cool stuff you can do with breakpoints in XCode. Such as: http://stavash.wordpress.com/2012/12/22/pimp-your-xcode-add-sound-to-breakpoints/ – Stavash Aug 09 '13 at 15:26
  • Wow, that's nice to know! Your example appears to show a property, though. Does it work on ivars as well as on properties? – Sergey Kalinichenko Aug 09 '13 at 15:26
  • It will work on whatever is evaluated to the expression you write within the specific scope of the breakpoint. – Stavash Aug 09 '13 at 15:27
  • See edited answer - for monitoring all changes in a single breakpoint use the second case. – Stavash Aug 09 '13 at 15:41
  • An even better approach - watchpoints! (see edited answer once again) – Stavash May 22 '14 at 06:40
8

Set a symbolic breakpoint. Go to the Breakpoint Navigator, click the +, click "Add Symbolic Breakpoint." In the first field, type -[YourSubclassNameHere setPosition:]", add any other setting you'd like to, then click outside the dialog.

5

Well the simple way to do it is right clicking on the variable in the watch window and selecting the watch variable option. Xcode will then alert you when the value is changed.

Or you could have a look at Key-Value Observing.

geekchic
  • 2,371
  • 4
  • 29
  • 41
2

You could override the setter of position to have a breakpoint when it sets the variable.

user2666713
  • 200
  • 9