iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Wednesday, August 4, 2010

Better NSLog implementation

NSLog is an invaluable tool for developers who are looking to debug and/or troubleshoot code. It outputs to the debugger console during the application runtime. Before I show a better way to use the NSLog function, let's go over the basics with an example:

int myInt = 100;
NSLog(@"The value of myInt: %i", myInt);
This will output:
The value of myInt: 100

Depending on what type of value you're trying to print, you'll have to use different Format Specifiers (%i in the previous example). Here's a list of common Format Specifiers:

Specifier Description
%@ Cocoa object with -description property
%d, %i Signed integer
%u Unsigned integer
%f Double or Float
%p Pointer
%s C String
%c Character
%ll Long Long
%Lf Long Double
%llu Unsigned Long Long
%x Hexadecimal
%o Octal

Now for the "Better NSLog" implementation, which I'm defining as spLog (choose any non-keyword, doesn't matter).
# define spLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
# define spLog(...)
This little macro takes NSLog a step further, by including the function name (in which the log call resides) and the line number, as well as whatever you were NSLogging in the first place. It is called in the same way NSLog is called. So the only difference from the first example would be:
int myInt = 100;
spLog(@"The value of myInt: %i", myInt);
This output would be:
-[myViewController myFunction:] [Line 56] The value of myInt: 100

So just include the macro in a header file and you're good to go. When you're debugging, the more information you get, the better and this is a quick way to get it.



Post a Comment

Subscribe to Post Comments [Atom]

<< Home

« Older Entries  
Newer Entries »