Sunday, July 8, 2012

Yet Another Debug Output (NSLog Replacement)

Although NSlog is convenient for outputting messages to the console, I tire of the date/time and object information that it prints.
As an alternative, one can craft a macro that uses CFShow, which outputs Core Foundation objects to stderr. CFShow uses callbacks to objects to display their descriptions, which allows one to use “%@” like you would when calling NSLog.
I often include the following debug definition as part of my projects:
#define debug(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
A few short examples follow showing the difference in output between NSLog and the debug macro shown above.
1
2
3
4
5
6
7
8
9
10
11
12
struct point
{
int x;
int y;
};
typedef struct point POINT;
 
POINT topLeft;
topLeft.x = 15, topLeft.y = 20;
 
NSLog(@"x: %d y: %d", topLeft.x, topLeft.y);
debug(@"x: %d y: %d", topLeft.x, topLeft.y);
The output will now look as follows:
Here’s another example, this time passing in an object:
1
2
3
4
5
6
7
8
9
10
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];
 
...
 
NSLog(@"Date: %@", dateString);
debug(@"Date: %@", dateString);
And the corresponding output:
Ahhh, much better.

No comments:

Post a Comment