Sunday, September 09, 2012

Get Caller Class Context and Caller Method Names

In my MyLog class, I prefer to print class name and method name in my log messages. What I did before was to use hard coded strings. This practice makes the maintenance difficult, specially when class or method names are changed.

Later I found two nice Cocoa C-Functions to achieve the same result, without any hard-coded strings. Those functions are great way to get context class and method names. Therefore, I added them to MyClass as convenient macros:


#define CALLER_SELECTOR_NAME NSStringFromSelector(_cmd)
#define CALLER_CONTEXT       NSStringFromClass([self class])

Here are examples to use CALLER_CONEXT to initialize MyLog instance and use CALLER_SELECTOR_NAME to get method name:

// ExampleClass1.m
#import "MyLogger.h"
...
@property (strong, nonatomic) MyLogger* logger;
...
@implementation ExampleClass1
...
@synthesize logger;
- (MyLogger *) logger {
   if (!_logger) {
       _logger = [[MyLogger alloc] initWithContext:CALLER_CONTEXT];
   }
   return _logger;
}
...
- (void) viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];

   [self.logger debug:
    ^{
        return [NSString stringWithFormat:@"'%@' is called!",
               CALLER_SELECTOR_NAME];
     }
   ];
...
}
...
@end

Here is the result in the debug console:

2012-09-09 14:23:44.990 TapToCount[5260:c07] [DEBUG] ExampleClass1 - 'viewWillAppear:' is called!

Reference

0 comments: