⇥ Quickie: a drop-in replacement for NSLog()

March 27, 2009
3 comments
 
⇥ Permalink

I came across this blog post mentioned in a couple of places, so I thought I’d offer my two cents and offer an alternative method of creating a drop-in replacement for NSLog().


The way I see it, there are two limitations with the approach mentioned in that blog entry:
  • You need to define a new switch (DEBUG)
  • You need to learn to use a new function, which makes it inconvenient to drop in the replacement in an existing project that makes extensive use of NSLog()
These are, of course, minor inconveniences—adding a new define is minimal work, and a global search-and-replace can take care of any existing NSLog() calls that need to be converted over to the new name.

Still, I am lazy enough that I use a slightly different approach:

#ifndef OPTIMIZE

# define NSLog(…) NSLog(@“[%s:%d]: %@”, FILE, LINE, [NSString stringWithFormat:VA_ARGS])

#else

# define NSLog(…) /* */

#endif


This has a couple of advantages:
  • The name NSLog() is not altered—and you get to continue using a function you are familiar with without any changes whatsoever
  • OPTIMIZE is already defined when you are building in the Release configuration, so you don’t need to create any new switches
Thus, if you drop these five lines of code in your .pch file, NSLog() will automatically be redefined to an empty line of code (just like in the post above) when building in Release, and be enhanced by printing the name and line of the source file where the call to it takes place as an added bonus.