views:

462

answers:

1

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.

+9  A: 

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.

Tom
Don't forget about NSInvocation for when you need more than 2 parameters.
dreamlax