Last Updated: February 25, 2016
· jordanbondo

Log messages with Xcode Breakpoints

Sometimes it's just not feasible to stop execution every time a breakpoint is hit. Say you're trying to debug something on a background thread that for whatever reason doesn't occur when you pause at a breakpoint.

The first thing I would normally think to do is to insert an NSLog statement to write to the console whatever it is that I happen to be interested in:

- (void)nothing
    TestObject* thing1 = [[TestObject alloc] init];
    TestObject* thing2 = [[TestObject alloc] init];
    NSInteger x = [self GetResult];
    if(x > 5)
        [thing1 DoThingy:x];
        NSLog(@"Did thingy on thing1 with x: %ld", x);
        [thing2 DoWhatsit:x];
        NSLog(@"Did whatsit on thing2 with x: %ld", x);

That's all fine and well, but now you have two NSLog statements. You might be OK with that if you know you're going to want to see the results of this every time you're debugging, but if you're just logging to debug until you get whatever it is worked out, then you have to remember to go back in there and remove the NSLog statements. If you have a lot of NSLog statements all over your codebase to debug this thing you're working on, it have to search for all of them and remove them and make sure you don't miss any before you commit or else somebody else on your team will walk over and punch you for having a bunch of irrelevant log message spewing out in their console. Bad times.

Luckily, you can use breakpoints to log a messages for you and automatically continue on! (I guess that's not really a "break" point, but whatever.)

In Xcode, set your breakpoint at the line you want and right click on it. Select "Edit Breakpoint" and you will get this popup:


Now click on the "Add Action" button and change the action to Log Message:


Type the message you want to be logged. You can have it include the results of an evaluated expression by surrounding the expression with "@" (I used @x@ to include just the value of x, but you could do something more complicated like @x > 10@ if you wanted to).

Finally, check the options box at the bottom of the dialog labeled "Automatically continue after evaluating"


That's it! Now you can enable & disable you logging breakpoints at will without having to type any NSLog statements, and to remove them you just drag them away (or visit the Breakpoints Navigator view and drag them out of there).

There's lots of other things you can do with breakpoints, so play around with the other actions and options that are available in the Edit Breakpoint dialog.