MMSGURU's Techno Blog | home | subscribe | contact | admin |
Wednesday, September 8th  
Debugging Macros on Cocoa (and Cocoa Touch)
Ahoi!

over the last 10 years I was coding a lot on Windows based systems using Visual C++. I grew custom to using the convenient TRACE and ASSERT macros.

When starting to do more cross-platform coding, I simply implemented my own versions of those macros and kept using them as learned.

Now that I started doing Cocoa coding, I missed my former buddies TRACE and ASSERT. But not for long as I discovered that there actually were very similar macros/functions existing on that platform (NSLog and NSAssert). However, both dont work exactly the way I used my old pals.

The differences are:
- NSLog and NSAssert are not strictly existing in DEBUG builds but in all versions of your code.
- NSAssert does not take a variable number of arguments but exists in several versions depending on the amount of paramaters you want to supply.


The first issue is a no brainer, all you need to do is create a wrapping macro an make sure it only exists when compiling your code in DEBUG mode. The second one isn't rocket science either as you can see below.

So once again, I wrote my own version of the good old friends from ancient (and possibly soon to be forgotten) times.

To use them as intended, add this header to your project and also make sure that you add the definition of _DEBUG to your DEBUG project settings: Project Info > Build > GCC_PREPROCESSOR_DEFINITIONS: _DEBUG=1



/*
* DebugBase.h
*
* Created by Till Toenshoff on 4/28/09.
* Copleft 2009 MMSGURU. No rights reserved.
*
*/
#include <stdarg.h>
#import <Foundation/Foundation.h>

#ifdef _DEBUG

#define TRACE(format, ...) NSLog(format, ## __VA_ARGS__)

void MyAssertLog (NSString *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
NSString *varString = [[NSString alloc] initWithFormat: fmt arguments: ap];
va_end(ap);
NSString *outputString = [[NSString alloc] initWithFormat: @"*** Assertion failure: %@", varString];
NSLog(outputString);
}

#define ASSERT(condition, desc, ...) \
if (!(condition)) { \
MyAssertLog(desc, ## __VA_ARGS__); \
} \
NSAssert(condition, @"see above");

#else

#define TRACE(format, ...)
#define ASSERT(condition, desc, ...)

#endif


Presto, the Windows coder feels much more at home on Mac OS as well as the new miraculous cash cow, the iPhone.

April 30th, 2009 - 01:33 pm | permalink