2

I have some constant strings defined in my @implementation file like:

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

Could I get the content of contentDisplayDateKeyPath use a string which holding the variable's name in runtime?

ex:

NSString *constantName = @"contentDisplayDateKeyPath"

[self valueForKey:constantName] 

then I'll get content.display_date

Can this be achieved?

I am trying to achieve this by using CFBundleGetDataPointer

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

But the stringPointer is always null.

Thanks for help

YCK
  • 65
  • 1
  • 1
  • 6

4 Answers4

2

This should do it for you.

NSString *__autoreleasing *string = (NSString*__autoreleasing*)dlsym(RTLD_DEFAULT, "<name of constant like PKPaymentNetworkVisa>");
NSLog(@"%@", *string);
Ian Bytchek
  • 8,804
  • 6
  • 46
  • 72
Matt Foley
  • 921
  • 1
  • 8
  • 24
0

Use a map with the key as the constant name and the value as the constant value:

static NSDictionary *_constants = @{

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

...

NSString *constantName = @"contentDisplayDateKeyPath";
NSString *constantValue = _constants[constantName];
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Thanks, I've already try your suggestion and this completely fulfills my needs. But I'm looking for another solution (like using CFBundleGetDataPointerForName) – YCK Nov 13 '13 at 10:10
0

Another option is to encapsulate this into a singleton object and access your constants through read only properties. Check out What should my Objective-C singleton look like? to see the singleton design pattern.

Community
  • 1
  • 1
Magic Bullet Dave
  • 9,006
  • 10
  • 51
  • 81
0

This question was answered here:

How do I lookup a string constant at runtime in Objective-C?

The solution worked perfectly for me.

You can use CFBundleGetDataPointerForName to lookup a constant's value at runtime

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

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