iphoneobjective-creflectionruntime

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.


Solution

  • 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.