6

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?

2 Answers 2

23
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
Sign up to request clarification or add additional context in comments.

Comments

4

You just have to use

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

here is also a related post

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.