Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

cocoa - How can I dynamically create a selector at runtime with Objective-C?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...