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.
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:
In the implementation file in the same place (above @interface and @implementation) declare this:
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.
or
etc etc – Using this convention is great for type safety. I use it all the time.