我在 SomeClass.h 中定义了一个类外常量:
extern NSString *const SCImportantString;
@interface SomeClass
@end
并在 SomeClass.m 中分配它:
NSString *const SCImportantString = @"All your base are belong to us.";
@implementation SomeClass
@end
有没有办法通过带有名称的字符串来访问这个外部常量?我知道使用 valueForKey:
的类和即时变量是可能的方法。
在使用不同的构建配置时执行此操作将非常有用。
最佳答案
如果明白你的意思,没有内置方法可以从字符串中获取 const 指针值......所以没有 NSConstantFromName(@"xy)
你自己也可以
NSString *const SCConstantByName(NSString *name) {
if[(name isEqualToString:@"SCImportantString"])
return SCImportantString;
}
或者对于许多人来说有一个静态字典...就像本地化也可以工作:
NSString *const SCConstantByName(NSString *name) {
id dict = nil;
if(!dict) {
dict = @{@"SCImportantString", SCImportantString};
return dict[name];
}
关于Objective-C – 使用包含其名称的字符串访问 extern const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883330/