简体   繁体   English

在Objective-C中动态加载类?

[英]Dynamically Load Classes in Objective-C?

Is there a way to #import a class from a string in Objective-C at run time? 有没有一种方法可以在运行时从Objective-C中的字符串中导入类? Any methods that would produce a similar result would also be welcome. 任何会产生类似结果的方法也将受到欢迎。

Edit: 编辑:

I want access to a class whose name I determine at runtime. 我想访问一个在运行时确定名称的类。 So something like this: 所以像这样:

NSString *className = getClassName();
Class myClass = loadClass(className);
myClass *myVar = [[myClass alloc] init];

Is there any way to do this without putting a static #import directive for myClass at the top of the file? 有什么方法可以在文件顶部没有为myClass放置静态的#import指令的情况下执行此操作?

You can use NSClassFromString method. 您可以使用NSClassFromString方法。 So: 所以:

// Creates an instance of an NSObject and stores it in anObject
id anObject = [[NSClassFromString(@"NSObject") alloc] init];

Some more sample code in response to your edit: 响应您的编辑的更多示例代码:

NSString* myClassString = getClassName();
// if the class doesn't exist, myClass will be Nil and myVar will be nil
Class* myClass = NSClassFromString(myClassString);
id myVar = [[myClass alloc] init];

The #import directive does not "import" a class — it inserts the text from the named file into the current file. #import指令不会“导入”一个类,而是将命名文件中的文本插入到当前文件中。 This obviously isn't useful at runtime after the source has been compiled. 显然,这在编译源之后在运行时没有用。

What you want is to create a bundle with the classes and dynamically load the bundle . 您想要的是使用类创建捆绑包并动态加载捆绑包 In order to be able to talk to the classes from the core program, you'll probably want to have some common protocol that bundled classes implement. 为了能够与核心程序中的类进行对话,您可能希望拥有捆绑类实现的一些通用协议。

感谢Chuck为我指明了正确的道路,但是此查询的正确答案似乎是在iOS 4.1上是不可能的,尽管当前的Mac OSX SDK使用可加载的包是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM