Is a static constructor equivalent in Objective-C?

I am new to Objective-C, and I have not been able to find out if the language has an equivalent static constructor, that is, a static method in a class that will be called automatically before the first instance of such a class. Or do I need to call the initialization code myself?

thank

+67
initialization static objective-c initializer
Jun 14 '09 at 3:25
source share
3 answers

The +initialize method is called automatically when you first use the class, before any class methods are used or instances. You should never call +initialize yourself.

I also wanted to go through a tidbit that I recognized that might bite you: +initialize inherited by subclasses and is also called for every subclass that does not implement +initialize its own . This can be especially problematic if you naively implement singleton initialization in +initialize . The solution is to check the type of the class variable as follows:

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

All classes that descend from NSObject have +class and -class that return a Class object. Since there is only one class object for each class, we want to check the equality with the == operator. You can use this to filter out what should happen only once, versus once for each individual class in the hierarchy (which may not yet exist) below that class.

For a tangential topic, you should learn about the following related methods, if you have not already done so:




Edit: Check out this post from @bbum, which explains more about +initialize : http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not- so-much /

In addition, Mike Ash wrote a nice detailed Friday Q&A about the +initialize and +load methods: https://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading- and-initialization.html

+119
Jun 14 '09 at 18:10
source share

There is a + initialize method that will be called before using the class.

+51
Jun 14 '09 at 4:58
source share

A little addition to this topic:

There is another way to create a “static constructor” in obj-c using the __attribute directive:

 // 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. // eg myStructDef.myVariable1 = "some C string"; myStructDef.myFlag1 = TRUE; // so when the user calls the code [MyClass createClassFromStruct:myStructDef], // myStructDef is not junk values. } 
+10
Jan 05 2018-12-12T00:
source share



All Articles