Research, Dev, Share

Logging class/method/variable name in Objective-C

Posted in Objective-C, Programming Language by Khang Vo on May 5, 2010

Just a small post for an effective tip in Objective-C.

Usually if you use the

NSString *name = @”Hello World”;

NSLog(@”%@”, name);.

Output: Hell world

And usually, when we debug the program and viewing the log, we really want to know the class/method/variable name and line number as well. You can manually hard code it like

NSLog(@”ApplicationDelegate – applicationDidFinishLaunching – name – Helloworld”);

But, it is really time consuming and repetitive task. For our company, we use


#define NCLog(s, ...) NSLog(@"<%@:%s:{%d}> %s = %@",
[[NSString stringWithUTF8String:__FILE__] lastPathComponent], \
 NSStringFromSelector(_cmd), __LINE__, #__VA_ARGS__ , \
 [NSString stringWithFormat:(s), ##__VA_ARGS__])

Another variant of this is (it combines both class name and method name into __FUNCTION__):

#define NCLog(s, ...) NSLog(@"<%s:{%d}> %s = %@", __FUNCTION__, __LINE__, \
 #__VA_ARGS__, [NSString stringWithFormat:(s), ##__VA_ARGS__])

Then you can just use it like NSLog. For example:

NCLog(@”Hello world”);

Output: <ApplicationDelegate:applicationDidFinishLaunching:100> name: Hello World

Good luck to your new productivity:). For your programming language, stop using the System.out.println() and Console.WriteLine, find a version of yourself

References:

http://stackoverflow.com/questions/2770307/log-the-method-name-in-objective-c

http://stackoverflow.com/questions/2818542/print-out-the-variable-name-objective-c

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: