Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor equivalent in Objective-C?

I'm new to Objective C and I haven't been able to find out if there is the equivalent of a static constructor in the language, that is a static method in a class that will automatically be called before the first instance of such class is instantiated. Or do I need to call the Initialization code myself?

Thanks

like image 764
Franklin Munoz Avatar asked Jun 14 '09 03:06

Franklin Munoz


2 Answers

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

I also wanted to pass along a tidbit I learned that can bite you down the road: +initialize is inherited by subclasses, and is also called for each subclasses that doesn't implement an +initialize of their 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 like so:

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

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

On a tangential topic, it's worth learning about the following related methods, if you haven't already:

  • - isMemberOfClass:(Class)aClass (true only for aClass itself)
  • - isKindOfClass:(Class)aClass (true for aClass and children)
  • + isSubclassOfClass:(Class)aClass (same as above, but a class method)

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

Also, 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

like image 149
Quinn Taylor Avatar answered Sep 21 '22 03:09

Quinn Taylor


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

like image 23
Nathan Kinsinger Avatar answered Sep 24 '22 03:09

Nathan Kinsinger