How do I debug with NSLog(@"Inside of the iPhone Simulator")?

I'm used to programming and having log messages be viewable. I know you used to be able to use NSLog() to trace out messages when debugging Cocoa applications. What is the best way to "trace" messages when coding in an iPhone Xcode development environment?


There's a far more convenient way to trace with log messages in Xcode, and that's using Breakpoint Actions.

On the line of code where you'd be tempted to add a printf or NSLog, set a breakpoint, then control-click it and choose "Edit Breakpoint". In the blue bubble that appears, click the + button on the right to open the Breakpoint Actions: alt text http://idisk.mac.com/cdespinosa/Public/Breakpoint%20Actions.png

Enter your log text there. Any expression that can be printed in the Debugger can be used when delimited by @ signs.

For debugging Objective-C it's generally more useful to choose "Debugger Command" from the popup and enter 'po [[object method] method]' to print the description string of an Objective-C object or the result of a method call.

Make sure to click the "Continue" checkbox at the top right so execution continues after the log.

Advantages of this over NSLog and printf:

  • It's on the fly. You don't have to recompile and restart to add or edit log messages. This saves you a lot of time.
  • You can selectively enable and disable them. If you learn enough from one, but its spew is interfering, just uncheck its Enabled box.
  • All the output is generated on your Mac, never on the iPhone, so you don't have to download and parse through logs after the fact.
  • The chance of shipping console spew in your application is significantly decreased.

Also check out the Speak button; it's great for debugging full-screen apps where you can't see the debug log.


Here's a great bit of code I picked up somewhere on the web. It defines new functions DLog() and ALog(). DLog messages only appear when the app is compiled with a -DDEBUG flag (define DEBUG). ALog messages ALWAYS appear (even in Release mode).

// DLog is almost a drop-in replacement for NSLog
// DLog();
// DLog(@"here");
// DLog(@"value: %d", x);
// Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead DLog(@"%@", aStringVariable);
#ifdef DEBUG
#       define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#       define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);