Objective-C load and initialize

These two static methods of an ObjC class allow you to run initialization logic where you can set up any static state. Both methods are only invoked if implemented and do not need to be declared in the interface of your classes. The differences between them are as follows:

  • In an application, or in a framework that links to an application, the +load() method is executed before the main(). In a loadable bundle, that same method is executed during the loading process. Instead, the +initialize() method is executed lazily before the first use of the class it belongs to.
  • There is no autorelease pool in place when the +load() method is executed, so if using any autoreleased objects you will have set one up yourselves. The +initialize() method runs in the same context as the first call you make to the enclosing class, so there will most likely be an autorelease pool present.
  • Because the +load() method is executed so early, you have to be careful because not all classes you rely on might have been loaded. All frameworks you link to are guaranteed to be loaded first, though, so you can rely on the classes they define. No such concern is necessary when using classes from within the +initialize() method.
  • Unlike all other cases (including the +initialize() method), when redefining a +load() method in a category, you will end up with all defined loaders being executed when an application starts or a bundle is loaded.

Leave a comment

Your email address will not be published. Required fields are marked *


*