1

I have a .h file that defines a few hundred constants. Let's assume this to be one of them:

#define KDSomeItem      1

I know that the Objective-C runtime API can be used to retrieve a list of instance variable names: like detailed in this question: How do I list all fields of an object in Objective-C? I also know that the getter [object valueForKey:theName] can be used to access the ivars as found in an earlier question of mine: How to access a property/variable using a String holding its name

My question is can something simmilar be done with constants? That is can I:

a) get a list of all constants programmatically

b) access a constant if I have a string holding its name

e.g. if I had a String like this NSString * theName = @"KDSomeItem"; could I evaluate my constant using this string?

Community
  • 1
  • 1
C.O.
  • 2,281
  • 6
  • 28
  • 51

2 Answers2

1

You would not be able to do this: unlike instance variables, #define-d constants do not leave a trace after the preprocessor is done with them. They leave no metadata behind - all instances of KDSomeItem in the body of your program will be replaced with 1 even before the Objective C compiler proper gets to analyze your code.

If you need the constant names to be available at run time, you would need to build all the necessary metadata yourself. In order to do that, you may want to look into "stringizing" operator of the preprocessor:

#define STR(X) #X

This macro can be applied to a preprocessor constant, and produce a C string literal with its name:

const char *nameOfKDSomeItem = STR(KDSomeItem); // same as "KDSomeItem"
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks, that explains it. I'll have to wait a few minutes before accepting the answer ;-) – C.O. Aug 24 '12 at 16:30
0

Nope. Your constant is a preprocessor macro. It is textually substituted into your source code where you use it.

Lawrence D'Anna
  • 2,998
  • 2
  • 22
  • 25