按名称调用Objective-C方法

时间:2009-07-07 07:34:17

标签: iphone objective-c reflection runtime

如果我拥有的是字符串形式的签名,我如何在Objective-C类的运行时调用方法:

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

请注意,方法名称可以在运行时更改,但参数数量保持不变 - 在此实例中为一个。

2 个答案:

答案 0 :(得分:26)

您可以使用以下内容:

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

如果您需要传递参数,还有performSelector:withObject:performSelector:withObject:withObject:方法。

答案 1 :(得分:0)

为了在对象c上进行反射来执行方法调用,只需使用此快速配方即可。 objC使我们能够在运行时检查对象是否支持特定接口。如果存在,此调用将动态发生。

Class classAPI = NSClassFromString(@"yourClassName");
SEL methodToPerformSelector = NSSelectorFromString(@"yourMethodName:");
NSMethodSignature *methodSignature = [classAPI methodSignatureForSelector: methodToPerform];
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];