Fra*_*noz 70 static initialization objective-c initializer
我是Objective C的新手,我无法确定语言中是否存在等效的静态构造函数,这是类中的静态方法,将在此类的第一个实例之前自动调用被实例化.或者我是否需要自己调用初始化代码?
谢谢
Qui*_*lor 128
在使用任何类方法或创建实例之前,首次使用类时会自动+initialize调用该方法.你永远不应该打电话给自己+initialize
我还想传递一个小知识,我学会了可以咬你的路:+initialize由子类继承,并且也为每个没有实现+initialize自己的子类调用.如果你天真地实现单例初始化,这可能会特别成问题+initialize.解决方案是检查类变量的类型,如下所示:
+ (void) initialize {
if (self == [MyParentClass class]) {
// Once-only initializion
}
// Initialization for this class and any subclasses
}
Run Code Online (Sandbox Code Playgroud)
所有来自NSObject的类都有返回对象的方法+class和-class方法Class.由于每个类只有一个Class对象,我们确实希望测试与==运算符的相等性.您可以使用它来过滤应该只发生一次的内容,而不是在给定类下面的层次结构中的每个不同类(可能尚不存在)中过滤一次.
在一个切线主题上,如果你还没有,那么值得学习以下相关方法:
aClass自身)aClass和children)编辑:查看@bbum的这篇文章,其中解释了更多关于+initialize:http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so- 许多/
另外,迈克·艾什写了一篇关于这些+initialize和+load方法的详细的周五问答:https:
//www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html
Ric*_*III 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.
}
Run Code Online (Sandbox Code Playgroud)