本文介绍了在运行时创建一个类 - 为什么NSClassFromString和objc_getclass返回nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过使用两者:

NSClassFromString and objc_getclass

返回一个类,所以我可以在运行时创建它,但是对于某些类,两个函数都返回nil,例如TestClass。请注意,NSClassFromString适用于99%的课程。

to return a class, so I can create it at runtime, but both functions return nil for some classes, for example "TestClass". Note that NSClassFromString works for me for 99% of classes.

如果我添加

[TestClass class];

在我调用NSStringFromClass或objc_getclass之前,它可以工作。如果我尝试使用类引用创建类,即:

before I call NSStringFromClass or objc_getclass it, it works. and if I try to just create the class using a class reference, i.e.:

[TestClass alloc];

它也有效。那么我如何强制类在运行时加载,所以NSClassFromString或objc_getclass不会返回nil?

it works too. So how can I force the class to load at runtime so NSClassFromString or objc_getclass will not return nil?

推荐答案

我遇到了同样的问题问题。在我的情况下,我有使用

I ran into this same problem. In my case I had code which was looking up the class using

Class aClass = objc_getClass("Foo");

当Foo类与我的AppDelegate在同一个项目包中时,它有效。

Which worked when the Foo class was in the same project bundle as my AppDelegate.

作为重构代码的一部分,我将Foo类和相关的模型类从AppDelegate项目中移出到一个更易于测试和重用的公共静态lib项目中。

As part of refactoring the code, I moved the Foo class and associated model classes out of the AppDelegate project into a common static lib project that would be easier to test and reuse.

当我将Foo类移动到libFooBar时,objc_getClass(Foo)现在返回nil而不是Foo类。

When I moved the Foo class into libFooBar the objc_getClass("Foo") now returned nil instead of the Foo class.

为了解决这个问题,我调用了我感兴趣的类,以便libFooBar中的类在Objective-C运行时中注册。我是这样做的:

To solve this, I put in call to the class I am interested in so that the classes from libFooBar are registered with the Objective-C runtime. I did this like so:

Foo* foo = [[Foo alloc] init];
[foo release];
Class aClass = objc_getClass("Foo");

现在objc_getClass(Foo)再次返回Foo类而不是nil。

Now the objc_getClass("Foo") returns the Foo class again instead of nil.

我只能假设在调用静态库中的某个类之前,静态库类没有注册。

I can only assume that the static library classes are not registered until a call to one of the classes in the static library is made.

这篇关于在运行时创建一个类 - 为什么NSClassFromString和objc_getclass返回nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:34