10

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.

teabot
  • 15,358
  • 11
  • 64
  • 79

2 Answers2

27

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.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Tom Jefferys
  • 13,090
  • 2
  • 35
  • 36
  • 11
    Don't forget about NSInvocation for when you need more than 2 parameters. – dreamlax Jul 07 '09 at 07:52
  • If you use `performSelector:withObject:`, be sure to end your method name with a colon. The method name without a colon matches a method with no parameters. – Douglas Lovell Jun 25 '13 at 13:31
  • Thanks [dreamlax](http://stackoverflow.com/users/10320/dreamlax)!. Here a [complete answer](http://stackoverflow.com/a/313455/1121497) about `NSInvocation`. – Ferran Maylinch Nov 30 '15 at 22:23
2

In order to perform methods invocation in reflection on objetive c just use this quick recipe. objC enabling us checking if an object supports a particular interface at runtime, This invocation happens dynamically if exists.

Class classAPI = NSClassFromString(@"yourClassName");
SEL methodToPerformSelector = NSSelectorFromString(@"yourMethodName:");
NSMethodSignature *methodSignature = [classAPI methodSignatureForSelector:methodToPerformSelector];
NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[myInvocation setTarget:classAPI];
[myInvocation setSelector:methodToPerformSelector]

/* if you have an argument */
[myInvocation setArgument:&someArgumentToAddToYourMethod atIndex:argumentIndexInMethod];
[myInvocation retainArguments];

[myInvocation invoke];
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
avivamg
  • 12,197
  • 3
  • 67
  • 61