Cocoa in the Shell

Improving NSLog()

When you debug an app, you often need to print informations on screen to check out if everything is ok etc… But when you are done and you are ready to release your application it’s a real pain in the ass to comment or remove all the call to these functions, plus they might be useful later.

To fix this problem you just need to define a macro that indicates if you are in a debug phase or not, if it’s the case, informations will be printed on the screen otherwise nothing will happen.
Not so long ago I found a article who just talked about this, and in the end a code was proposed :

#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

Place this code in your Prefix.pch file, and it’s almost done ;)

The last thing you have to do is to define the DEBUG macro. In Xcode go to project information, chose Debug configuration and in the Preprocessing part look for the line Preprocessor Macros and add it : DEBUG=1

DLog() works exactly like NSLog(), so you can pass arguments etc… the advantage is that the line and the function name will be printed thanks to __PRETTY_FUNCTION__ and __LINE__ macros.

As for the macro ALog(), it remplaces NSLog() and will always produce an output.