gpt4 book ai didi

objective-c - 从字符串动态调用类的静态方法

转载 作者:太空狗 更新时间:2023-10-30 03:39:07 24 4
gpt4 key购买 nike

我有两个字符串:

NSString * className = "MyClass";
NSString * methodName = "doSomething";

MyClass 类定义和 static 方法 doSomething 也存在。

如何从两个字符串动态触发 [MyClass doSomething]?

最佳答案

Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");
[class performSelector:selector];

这会给你一个警告“PerformSelector 可能会导致泄漏,因为它的选择器是未知的”,你可以像这样忽略它(详见 this question):

Class class = NSClassFromString(@"MyClass");
SEL selector = NSSelectorFromString(@"doSomething");

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[class performSelector:selector];
#pragma clang diagnostic pop

关于objective-c - 从字符串动态调用类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com