问题
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.
回答1:
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];
}
来源:https://stackoverflow.com/questions/13883330/objective-c-access-extern-const-with-a-string-containing-its-name