1

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";
Ohad Regev
  • 5,641
  • 12
  • 60
  • 84

2 Answers2

3

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.

βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • # has special meaning when used in a macro. # means quote the following token (which should be a macro parameter name). your macro is same as NSLog( @"%s","aNumber"); – Parag Bafna Jul 25 '13 at 08:34
0

In most programming languages objects don't have names.

Parag Bafna
  • 22,812
  • 8
  • 71
  • 144