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]) {
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
Quinn Taylor Jun 14 '09 at 18:10 2009-06-14 18:10
source share