繁体   English   中英

如何使用保存其名称的字符串在运行时访问常量字符串?

[英]How to access constant string in runtime using a string which holding its name?

我在@implementation 文件中定义了一些常量字符串,例如:

static NSString * const contentDisplayDateKeyPath   = @"content.display_date";
static NSString * const contentIDKeyPath            = @"content.id";

我可以使用一个在运行时保存变量名称的字符串来获取 contentDisplayDateKeyPath 的内容吗?

前任:

NSString *constantName = @"contentDisplayDateKeyPath"

[self valueForKey:constantName] 

然后我会得到 content.display_date

这能实现吗?

我试图通过使用 CFBundleGetDataPointer 来实现这一点

    CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(CFBridgingRetain([[NSBundle mainBundle] bundleIdentifier]));
    void *stringPointer = CFBundleGetDataPointerForName(mainBundle, CFBridgingRetain(obj));
    NSString *string = (__bridge NSString *)stringPointer;

但 stringPointer 始终为空。

感谢帮助

这应该为你做。

NSString *__autoreleasing *string = (NSString*__autoreleasing*)dlsym(RTLD_DEFAULT, "<name of constant like PKPaymentNetworkVisa>");
NSLog(@"%@", *string);

使用以键为常量名、以值为常量值的映射:

static NSDictionary *_constants = @{

    @"contentDisplayDateKeyPath" : @"content.display_date",
    @"contentIDKeyPath"          : @"content.id",
    // etc.
};

...

NSString *constantName = @"contentDisplayDateKeyPath";
NSString *constantValue = _constants[constantName];

另一种选择是将其封装到一个单例对象中,并通过只读属性访问您的常量。 看看我的 Objective-C 单例应该什么样的? 查看单例设计模式。

这个问题在这里得到了回答:

如何在 Objective-C 中在运行时查找字符串常量?

该解决方案对我来说非常有效。

您可以使用CFBundleGetDataPointerForName在运行时查找常量的值

-(NSString *)lookupStringConstant:(NSString *)constantName 
{

    void ** dataPtr = CFBundleGetDataPointerForName(CFBundleGetMainBundle(), (__bridge CFStringRef)constantName);
    return (__bridge NSString *)(dataPtr ? *dataPtr : nil);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM