I have two strings:
NSString * className = "MyClass";
NSString * methodName = "doSomething";
MyClass class definition and static method doSomething also exists.
How can I trigger [MyClass doSomething] dynamically, from two strings?
Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");
[class performSelector:selector];
This will get you a warning "PerformSelector may cause a leak because its selector is unknown", which you can ignore like this (see this question for details):
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
You just have to use
[NSClassFromString(className) performSelector:NSSelectorFromString(methodName)];
here is also a related post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With