15

Continued from the last question here: Log method name in Obj-C . I just wondered if there is a way to print out the variable name as well. For example:

NSString *name = "vodkhang";
NCLog(@"%@", name);

and I hope that the output should be:

name: vodkhang

Just to summarize the previous post, currently, I can print out the class name, method name and the line number when I call

NCLog(@"Hello World");
<ApplicationDelegate:applicationDidFinishLaunching:10>Hello world

with

#define NCLog(s, ...) NSLog(@"<%@:%d> %@", __FUNCTION__, __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__])
Community
  • 1
  • 1
vodkhang
  • 18,639
  • 11
  • 76
  • 110

1 Answers1

36
#define logIntVariable(x) NSLog( @"Value of %s = %d",#x, x)


- (void) myRoutine {
   int intValue = 5;

   logIntVariable(intValue);
}
vodkhang
  • 18,639
  • 11
  • 76
  • 110
gnasher
  • 1,513
  • 12
  • 17
  • 12
    The general principle is that when you put a `#` in front of an argument within the body of a `#define`, the preprocessor replaces it with a C string of the *exact* expression passed to the macro. When you pass a variable name, you'll get that name. If you pass an expression, it will reproduce the expression in full, not the evaluated result. – Quinn Taylor May 13 '10 at 04:56