2

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • 1
    I don't really understand the question - isn't this just a global variable? You access the global variable and get a value back? What does the extra layer of indirection get you? And if you need access via a key then a Dictionary seems to be the obvious way to go; what is wrong with a dictionary? What problem are you trying to solve? – Robotic Cat Apr 08 '15 at 15:41
  • I'm trying to link the global variable to a cell identifier in a storyboard. – Alex Stone Apr 08 '15 at 16:14

2 Answers2

1

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.

Avt
  • 16,927
  • 4
  • 52
  • 72
-1

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.

Dare
  • 2,497
  • 1
  • 12
  • 20
  • 1
    This misses the point of the question. The OP appears to want to access the constant at runtime using a dynamic reference at runtime, not a hardcoded reference (as shown in your answer). – rmaddy Apr 08 '15 at 15:56