0

Is it possible to dynamically reference a constant in objective c:

e.g. NSForegroundColorAttributeName is declared in UIKit/NSAttributedString.h as a const NSString. Its value is @"NSColor". In compiled code, I just specify the constant to use it, but what if I need to refer to it dynamically at run time (say a user might type it out)?

I could just use @"NSColor", but that may change as the SDK changes.

Is there a function like NSClassFromString, say ConstFromString:

ConstFromString(@"NSForegroundColorAttributeName") --> @"NSColor"
  • 1
    In which scenarios would a user be typing in a constant name? I'm not sure what your use-case is here, but it sounds like a worse user experience than presenting a value spinner + colour-picker. – Ian MacDonald Jan 30 '15 at 18:25
  • E.g. being able to tweak the color of a label remotely (say the app hits a url that returns `{"textLabel.attributedText.attributes. NSForegroundColorAttributeName":"0xFFFFFF"}`. No recompilation/app update needed – Sara Lewis Jan 30 '15 at 18:50
  • Since you can't assign attributed text attributes exactly like your input, you're going to have to have logic run after the initial parsing of the input anyway, so why not just put in a switch/case for `attributes` keys? – Ian MacDonald Jan 30 '15 at 18:52
  • In that case you'll want to just define your json scheme to be something simple: `"myControl" : { "color" : "0xFFFFFF" }` and then in your code you map `"color"` to `NSForegroundColorAttributeName`. Since your code is compiled against a specific SDK, this will always work. – i_am_jorf Jan 30 '15 at 18:53
  • @jeffamaphone agreed. But the mappings have to be defined manually, there's no lookup function for NSForegroundColorAttributeName? – Sara Lewis Jan 30 '15 at 18:55
  • @IanMacDonald just wanted to save on some extra tedious typing=potential for mistakes – Sara Lewis Jan 30 '15 at 18:58
  • No, but you could always use the `textColor` property and use `NSSelectorFromString()` if you really can't stand having to type out a property mapping. Or get an intern to do it. – i_am_jorf Jan 30 '15 at 19:04
  • See also [ObjC access extern const with a string containing its name](http://stackoverflow.com/q/13883330) – jscs Jan 30 '15 at 19:48

1 Answers1

0

If the symbol is a public, exported symbol, then you might be able to look it up at runtime using dlsym and friends, but I agree with the commenter that this sounds like a bad idea.

ipmcc
  • 29,581
  • 5
  • 84
  • 147