Objective-C – access extern const with a string containing its name? [duplicate]

走远了吗. 提交于 2019-12-10 23:50:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!