Dynamically call a static method in a class from a string

I have two lines:

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

The definition of the MyClass class and the static doSomething method also exist.

How can I dynamically run [MyClass doSomething] from two lines?

+4
source share
2 answers
Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");
[class performSelector:selector];

This will give you a warning “PerformSelector may cause a leak because its selector is unknown”, which you can ignore (see 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
+21
source

You just need to use

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

here is also a related post

+4
source

All Articles