2

I have a constant defined out of class in SomeClass.h:

extern NSString *const SCImportantString;

@interface SomeClass

@end

And assign it in SomeClass.m:

NSString *const SCImportantString = @"All your base are belong to us.";

@implementation SomeClass

@end

Is there a way to access this extern constant by a string with its name? I know this is possible with class and instant variables using the valueForKey: method.

It would turn very useful to do this while using different build configurations.

Stepan Hruda
  • 596
  • 5
  • 12
  • Why don't you create a dictionary for that? – Anoop Vaidya Dec 14 '12 at 17:20
  • Could you be more specific? I would basically like to access this constant from code simply by using `SCImportantString` (as preferred in iOS frameworks), as well as simply have strings `SCImportantString` and `SCDifferentImportantString` in a setting for different build configurations. I want to avoid putting the content of the constant there literally, because when someone changes the content, he will definitely forget to change it in the build configuration. – Stepan Hruda Dec 14 '12 at 17:28
  • Or simply use #define... – Anoop Vaidya Dec 14 '12 at 17:33
  • That's exactly what I'm trying to avoid. – Stepan Hruda Dec 14 '12 at 17:37

1 Answers1

2

If get what you are saying there is no builtin way to get the const pointer value from a string ... so there isnt NSConstantFromName(@"xy)

you could it yourself though

NSString *const SCConstantByName(NSString *name) {
    if[(name isEqualToString:@"SCImportantString"])
        return SCImportantString;
}

or for many have a static dict... like the localizables also work:

NSString *const SCConstantByName(NSString *name) {
    id dict = nil;
    if(!dict) {
        dict = @{@"SCImportantString", SCImportantString};

    return dict[name];
}
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135