Search code examples
objective-cinstance-variablesintrospection

Objective-C >> Is There a Way to Get a Pointer / Variable Name as an NSString?


Is there a way to ask a pointer / variable for its name as a string?

i.e...

NSNumber* aNumber;
int anInt;

NSString* name = aFunctionThatDoesWhatIAskedFor(aNumber);
NSLog(@"%@",name); //should print "aNumber";

name = aFunctionThatDoesWhatIAskedFor(anInt);
NSLog(@"%@",name); //should print "anInt";

Solution

  • define this macro

    #define nameOfVariable(x) NSLog( @"%s",#x)
    

    use this macro

    nameOfVariable(aNumber);
    nameOfVariable(anInt);
    

    Explanation:

    Preceding parameter name by # is known as Stringification. You can use the ‘#’ operator to stringify the variable argument or to paste its token with another token.

    Sometimes you may want to convert a macro argument into a string constant. Parameters are not replaced inside string constants, but you can use the #' preprocessing operator instead. When a macro parameter is used with a leading#', the preprocessor replaces it with the literal text of the actual argument, converted to a string constant. Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification.