按名称调用 Objective-C 方法

发布于 2024-07-26 11:14:10 字数 234 浏览 3 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾城花音 2024-08-02 11:14:10

您可以使用类似以下内容:

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

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

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.

℉服软 2024-08-02 11:14:10

为了在 Objective C 上进行反射执行方法调用,只需使用这个快速方法。 objC 使我们能够在运行时检查对象是否支持特定接口,如果存在,则此调用会动态发生。

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];

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文