Objective-C 中的静态构造函数等价物? ?

我是 Objective C 的新手,我还没有能够找出语言中是否有静态构造函数的等价物,这是一个类中的静态方法,在这个类的第一个实例被实例化之前,它会被自动调用。还是需要我自己调用初始化代码?

谢谢

24901 次浏览

在使用类之前将调用 + 初始化类方法。

第一次使用类时,在使用任何类方法或创建实例之前,+initialize方法被称为 自然而然地。你永远不应该自己打电话给 +initialize

我还想告诉大家一个我学到的小道消息: +initialize由子类继承,并且对于没有实现自己的 +initialize的每个子类也调用 +initialize。如果您在 +initialize中天真地实现单例初始化,这可能会造成特别的问题。解决方案是像下面这样检查 class 变量的类型:

+ (void) initialize {
if (self == [MyParentClass class]) {
// Once-only initializion
}
// Initialization for this class and any subclasses
}

从 NSObject 下降的所有类都有返回 Class对象的 +class-class方法。因为每个类只有一个 Class 对象,所以我们确实希望用 ==操作符测试相等性。您可以使用它来过滤应该发生的事情,但是只能过滤一次,而对于给定类下面的层次结构中的每个不同类(可能还不存在) ,只能过滤一次。

如果你还没有了解过以下相关的方法,那么对于一个无关紧要的话题,这些方法是值得学习的:


编辑: 查看 @ bbum的这篇文章,它解释了更多关于 +initialize的内容: < a href = “ https://web.archive ve.org/web/20201108095221/http://www.friday.com/bbum/2009/09/06/iniailize-can-be-execute-multi-times-load-not-so-much/”rel = “ nofollow norefrer”> https://web.archive.org/web/20201108095221/http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/

此外,Mike Ash 写了一篇关于 +initialize+load方法的详细的周五问答: Https://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html

关于这个话题的一点补充:

在 obj-c 中创建“静态构造函数”的另一种方法是使用 __attribute指令:

// prototype
void myStaticInitMethod(void);


__attribute__((constructor))
void myStaticInitMethod()
{
// code here will be called as soon as the binary is loaded into memory
// before any other code has a chance to call +initialize.
// useful for a situation where you have a struct that must be
// initialized before any calls are made to the class,
// as they would be used as parameters to the constructors.
// e.g.
myStructDef.myVariable1 = "some C string";
myStructDef.myFlag1 = TRUE;


// so when the user calls the code [MyClass createClassFromStruct:myStructDef],
// myStructDef is not junk values.
}