如何在运行时使用Objective-C动态创建选择器?

时间:2020-03-06 14:31:07  来源:igfitidea点击:

我知道如何在编译时使用@selector(MyMethodName :)创建一个SEL,但是我想做的是从NSString动态创建一个选择器。这有可能吗?

我可以做什么:

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

我想做什么:(伪代码,这显然行不通)

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

我一直在搜索Apple API文档,但是还没有找到一种不依赖于编译时@selector(myTarget :)语法的方法。

解决方案

我不是Objective-C程序员,而是同情者,但也许我们需要NSSelectorFromString。在运行时参考中明确提到,我们可以使用它将字符串转换为选择器。

根据XCode文档,psuedocode基本上可以正确处理它。

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);`

编辑:Bu,太慢了。 :P