4

Consider,

NSString *myString = @"Welcome";

NSLog(@"%@",myString);

will print Welcome in console.

Can I print the string like "myString: Welcome"?

I mean, can I get the object name("myString") along with object value("Welcome")?

Confused
  • 3,846
  • 7
  • 45
  • 72

1 Answers1

6

Use the following code:

#define stringVariable(x) NSLog( @"%s:%@",#x, x) 

NSString *myString=@"Welcome";

stringVariable(myString); 

Note: 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.

Ashok Londhe
  • 1,491
  • 11
  • 29
  • 2
    This is correct, but I'd advise to use a different macro name. `stringVariable` might conflict with existing variable names. And since it is a macro, it might cause tricky and not obvious errors. Usually, all-uppercase is used for macros. In conjunction with a prefix, it should be more or less safe. Something like `CF_LOG_OBJECT_VARIABLE(x)`. You don't have to type it anyway. Viva la autocomplete :) – FreeNickname Apr 27 '15 at 11:00
  • @FreeNickname Thanks for suggestion next time sure i will do that. – Ashok Londhe Apr 27 '15 at 11:25
  • @AshokLondhe Just for the clarification. I tried the above code and its worked. But when I try this without defining it as macro, means I tried "NSLog( @"%s:%@",#myString, myString) " and it throws an error "Expected expression". Any idea? – Confused Apr 27 '15 at 11:55
  • Yes.. Because of that i have declare that as a macro. i thing only solution to it is macro. – Ashok Londhe Apr 27 '15 at 11:57