Compiled Chronicles

A software development blog by Angelo Villegas

Snippets: NSLog and Macros Tips and Tricks

Tricks

Some NSLog tricks I’m using on my escapade. These snippets are preprocessor macros that will help your debugging moments easier if not a lot.

ALog

This snippet will log everything every time you use it in a line. It will display the method name, the line number and the argument you gave.

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

This snippet will log everything every time you are in a DEBUG mode but has the same function of ALog.

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

This snippet will not take any arguments but will display the current file and method and the line number if you are in a DEBUG mode.

UALog

This snippet is much like DLog. It will take an argument and will display it, but in this case, it will display it using a UIAlertView instead of displaying it on the console.

#ifdef DEBUG
	#define UALog(fmt, ...)  { UIAlertView *alert = [[UIAlertView alloc] initWithTitle: [NSString stringWithFormat: @"%s\n[Line %d]", __PRETTY_FUNCTION__, __LINE__] message: [NSString stringWithFormat: fmt, ##__VA_ARGS__]  delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles: nil]; [alert show]; }
#else
	#define UALog(...)
#endif

The debugging process is tough, especially if you didn’t write the program yourself or the error code is a little obscure, misleading, or not enough details to process. By the help of these macros, it can help narrow down most of the problems that needs to be debugged.

Tips

Most of the preprocessor macros have obscure codes such as __PRETTY_FUNCTION__ and __LINE__. This are called C predefined macros that can be of great help not just in debugging but on other purposes such as displaying nice error messages, returning date and time, etc.

There are two types of macros, object-like and function-like. Object-like macros do not take parameters; function-like macros do.

Standard Predefined Macros

The standard predefined macros are specified by the relevant language standards, so they are available with all compilers that implement those standards. Older compilers may not provide all of them. Their names all start with double underscores.

Certain symbols are required to be defined by an implementation during preprocessing. These include __FILE__ and __LINE__, predefined by the preprocessor itself, which expand into the current file and line number.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *