Objective C 使用字符串动态调用方法

发布于 2024-10-07 15:27:11 字数 446 浏览 0 评论 0原文

我只是想知道是否有一种方法可以调用一个方法,我可以用字符串动态构建方法的名称。

例如,我有一个名为 loaddata 的方法

-(void)loadData;

来调用它,我通常会这样称呼它

[self loadData];

,但我希望能够使用字符串动态调用它,例如,

NSString *methodName = [[NSString alloc] initWithString:@"loadData"];
[self methodName];

这是一个愚蠢的例子,但我希望你明白我的意思。我将它用于为我的 iPad 应用程序设置的数据绑定类。很难解释,但要让它启动,我需要弄清楚如何使用字符串调用方法。

有什么想法吗?

谢谢

Im just wondering whether there is a way to call a method where i build the name of the method on the fly with a string.

e.g. I have a method called loaddata

-(void)loadData;

to call this i would normally call it like

[self loadData];

But i want to be able to call it dynamically with a string e.g.

NSString *methodName = [[NSString alloc] initWithString:@"loadData"];
[self methodName];

This is a stupid example but i hope you get my point. I am using it for databinding classes that I am setting up for my IPad application. Hard to explain but to get it to fire I need to work out how to call a method with a string.

Any ideas?

Thanks

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

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

发布评论

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

评论(2

断舍离 2024-10-14 15:27:11

你可以尝试类似的东西

SEL s = NSSelectorFromString(selectorName);
[anObject performSelector:s];

You can try something like

SEL s = NSSelectorFromString(selectorName);
[anObject performSelector:s];
魂牵梦绕锁你心扉 2024-10-14 15:27:11

您可以使用 objc_msgSend 函数。它需要两个参数,接收者和发送给它的选择器:

objc_msgSend(self, someSelector);

您需要使用 NSSelectorFromString 将字符串转换为适当的选择器:

NSString *message = [self getSomeSelectorName];
objc_msgSend(self, message);

该方法还需要可变数量的参数,因此您可以发送带有任意数量参数的消息。

NSString *message = [self getSomeSelectorNameWithManyArguments];
objc_msgSend(self, message, arg1, arg2, arg3, arg4);

You can use the objc_msgSend function. It takes two parameters, the receiver and the selector to send to it:

objc_msgSend(self, someSelector);

You'll need to turn your string into the appropriate selector using NSSelectorFromString:

NSString *message = [self getSomeSelectorName];
objc_msgSend(self, message);

The method also takes a variable number of arguments, so you can send messages with any number of arguments.

NSString *message = [self getSomeSelectorNameWithManyArguments];
objc_msgSend(self, message, arg1, arg2, arg3, arg4);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文