72

我是Objective C的新手,我无法找出语言中是否存在等效的静态构造函数,即类中的静态方法,将在此类的第一个实例之前自动调用被实例化。还是我需要自己调用初始化代码?

谢谢

4

3 回答 3

132

在使用任何类方法或创建实例之前,第一次使用类时会自动+initialize调用该方法。你永远不应该给自己打电话。+initialize

我还想传递一个我学到的花絮,它可以让你在路上吃到:+initialize被子类继承,并且也被每个没有实现+initialize它们自己的子类调用。如果您天真地在+initialize. 解决方案是检查类变量的类型,如下所示:

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

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

在一个切题的话题上,如果您还没有学习以下相关方法,则值得学习:


编辑:查看@bbum的这篇文章,其中解释了更多关于+initializehttp ://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-很多/

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

于 2009-06-14T18:10:02.283 回答
51

在使用类之前会调用+initialize类方法。

于 2009-06-14T04:58:53.010 回答
10

这个主题的一些附录:

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

// 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.
}
于 2012-01-05T14:39:28.670 回答