views:

3460

answers:

2

I know how to create a SEL at compile time using @selector(MyMethodName:) but what I want to do is create a selector dynamically from an NSString. Is this even possible?

What I can do:

SEL selector = @selector(doWork:);
[myobj respondsToSelector:selector];

What I want to do: (pseudo code, this obviously doesn't work)

SEL selector = selectorFromString(@"doWork");
[myobj respondsToSelector:selector];

I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time @selector(myTarget:) syntax.

+22  A: 

I'm not an Objective-C programmer, merely a sympathizer, but maybe NSSelectorFromString is what you need. It's mentioned explicity in the Runtime Reference that you can use it to convert a string to a selector.

Torsten Marek
I need to brush up on my Google-fu. that's exactly what I was (or wasn't as it may be) looking for.
craigb
Well, I still had the links flying around in my bookmarks since I've read through the Objective-C 2.0 docs a couple of days ago.
Torsten Marek
+9  A: 

According to the XCode documentation, your psuedocode basically gets it right.

It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. However, in some cases, a program may need to convert a character string to a selector at runtime. This can be done with the NSSelectorFromString function:

setWidthHeight = NSSelectorFromString(aBuffer);

Edit: Bummer, too slow. :P

Josh Gagnon