Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking an Objective-C method by name

How can I invoke a method at runtime on an Objective-C class when all I have is it's signature in string form:

NSString* typeName = @"Widgets";
NSString* methodName = [NSString stringWithFormat:@"add%@Object:", typeName];

Note that the method name can change at runtime but the number of arguments stays fixed - one in this instance.

like image 911
teabot Avatar asked Jul 07 '09 07:07

teabot


People also ask

Can I use C in Objective-C?

You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.


1 Answers

You can use something like the following:

SEL selector = NSSelectorFromString(methodName);
[myObject performSelector:selector];

There are also performSelector:withObject:, and performSelector:withObject:withObject: methods if you need to pass parameters.

like image 160
Tom Jefferys Avatar answered Oct 14 '22 04:10

Tom Jefferys