Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically call static method on class from string

Tags:

objective-c

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?

like image 563
knagode Avatar asked Dec 05 '13 12:12

knagode


2 Answers

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
like image 79
DrummerB Avatar answered Sep 22 '22 20:09

DrummerB


You just have to use

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

here is also a related post

like image 32
Alex Cio Avatar answered Sep 20 '22 20:09

Alex Cio