从string动态调用类的静态方法

时间:2013-12-05 12:42:26

标签: objective-c

我有两个字符串:

NSString * className = "MyClass";
NSString * methodName = "doSomething";

MyClass类定义和静态方法doSomething也存在。

如何从两个字符串动态触发[MyClass doSomething]?

2 个答案:

答案 0 :(得分:21)

Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");
[class performSelector:selector];

这会给你一个警告“PerformSelector可能导致泄漏,因为它的选择器未知”,你可以忽略这一点(详见this question):

Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");    

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[class performSelector:selector];
#pragma clang diagnostic pop

答案 1 :(得分:4)

你只需要使用

[NSClassFromString(className) performSelector:NSSelectorFromString(methodName)];

这里也是related post