Search code examples
iosnslogobjectname

NSLog - How to print object name?


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")?


Solution

  • 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.