Monday, August 29, 2005

Logging method invocations in Objective C

Here is a code fragment I use to log method invocations in Objective-C. The great advantage of Objective-C is that you can find out what the name of the method is that is executing. I don't believe this is possible in a language like Java.

QSLogMethodInvocation macro
// Prints a line in the console stating the name of the
// method that is invoked.
//
// For example if class Foo has a method bar, the definition
// of bar in the class Foo could contain QSLogMethodInvocation().
// The following message will be logged: Invoked bar from class Foo
#define QSLogMethodInvocation()\
NSLog(@"[LOG] Invoked %@ from class %@",\
[NSString stringWithCString:(char *)_cmd], [self class])


QSLogAbstractMethodInvocationError macro
// Prints a line in the console stating an abstract method
// was invoked.
//
// For example if class Foo has an abstract method bar,
// the definition of bar in the class Foo should contain
// QSLogAbstractMethodInvocationError().
// The following message will be logged:
// Error (Foo): abstract method bar invoked
#define QSLogAbstractMethodInvocationError()\
NSLog(@"[LOG] Error (%@): abstract method %@ invoked",\
[self class], [NSString stringWithCString:(char *)_cmd])

2 comments:

Anonymous said...

This is possible when using some AOP-language together with Java (for example AspectJ)

Damien said...

You're right. I noticed this last week in a class I had about AOP.