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?
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 ofKDSomeItemin the body of your program will be replaced with1even 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:
This macro can be applied to a preprocessor constant, and produce a C string literal with its name: