Can I access an ObjC constant by string name at runtime?

530 Views Asked by At

I know that Objective-C allows me to refer to selectors by name using @selector(@"name") How can I access the following constant by name at runtime? In other words, I would pass @"CONST_KEY" somewhere and get @"key" back.

const NSString* CONST_KEY = @"key";

I think I can do this by first creating a key-value dictionary and then querying it at runtime, but I'm not sure if there's a better implementation.

To clarify with a specific use case:
I want to use a collection view cell reuse identifier @"CONST_KEY", declared in my storyboard, and to be able to use this identifier to look up the value of CONST_KEY at runtime.

This way I hope to have a single place within my code to modify constants, rather than having to re-assign values in multiple classes. Having the two values linked will allow me to have a single action for all those cells using the CONST_KEY to define the action they are going to do.

2

There are 2 best solutions below

1
On

You don't need to call a selector to get the constant, you just need to expose it to your other classes. Also the constant should live inside of its relevant class. The method I use is the following.

in the header file right below your import statements (before @interface) declare this:

extern NSString *const CONST_KEY;

In the implementation file in the same place (above @interface and @implementation) declare this:

NSString *const CONST_KEY = @"key";

After you do that, in any class that imports the class where you declared your constant, you will be able to reference it simply with CONST_KEY

E.G.

[someDictionary objectForKey: CONST_KEY];

or

NSLog(@"%@", CONST_KEY); 

etc etc – Using this convention is great for type safety. I use it all the time.

0
On

Objective C is just a C with added object functionality. So "CONST_KEY" constant name is discarded during compilation. So you have to create your own class or use an NSDictionary to provide "constant_name"->"constant_value" functionality.