NSLog is a trace function. In short this emulates the concision of System.out.println() (java) without losing anything to the elegance of trace() (AS2/3).

Using NSLog

There seems to be scores of forum posts about NSLog not working with XCode, and even fixes for the problem. But hey, for the rest of us, NSLog works perfectly with XCode and CocoaTouch. You include something like:

// Print 'Hello 1st console output' to the console
NSLog("Hello %ist console output",1);

While a project is open, select Run >> Console to view NSLog output.

NSLog with Macros

I suggested earlier that there might be reasonable uses of macros. I’m reading somewhere that the C preprocessor is a *steaming turd*, so let’s have it. Try this:

#define print(...) NSLog(@__VA_ARGS__)
// Print 'Hello 2nd console output' to the console
print("Hello %ind console output",2);

The little more than notational convenience here is that you can easily and efficiently remove all logs from a production build by commenting out NSLog(@__VA_ARGS__) in the macro definition.

Removing annoying log output

By default, NSLog will output information about the current process along with a time stamp for every output from NSLog. Usually this is clutter. If you dump the “JANSLogHack” code in an .m file associated with your project, that will remove all this stuff. This is gracefully provided by Jens Ayton as a public domain utility.

#ifndef NDEBUG
#import <Foundation/Foundation.h>
#import <stdio.h>

extern void _NSSetLogCStringFunction(void (*)(const char *string, unsigned length, BOOL withSyslogBanner));

static void PrintNSLogMessage(const char *string, unsigned length, BOOL withSyslogBanner){
   puts(string);
}

static void HackNSLog(void) __attribute__((constructor));
static void HackNSLog(void){
  _NSSetLogCStringFunction(PrintNSLogMessage);
}
#endif

Stripping traces off release builds

Keeping traces in releases builds isn’t a good idea as they can seriously slow down code execution. I’m not covering this here, but you could check this article from the iphone development blog.

How about using the debugger

You might be inspired to try the XCode debugger in many situations where you would trace stuff. The debugger lets you set breakpoints to interrupt your program while running and – seriously useful – check the content of variables and objects by hovering over your source with the mouse. I often find this significantly faster and cleaner than using traces.