4

In Objective-C, what gets called before main? For example, I assume all metaclasses in Objective-C get instantiated before main and their load/initialize methods called, global constants, etc. What else? Is this documented anywhere?

Boon
  • 40,656
  • 60
  • 209
  • 315

1 Answers1

2

A +load method which is part of any class in your application (not in any loaded framework) will be executed before main(). The full order of execution is given in the +load documentation (NSObject class reference):

The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.

The order of initialization is as follows:

• All initializers in any framework you link to.

• All +load methods in your image.

• All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.

• All initializers in frameworks that link to you.

In addition:

• A class’s +load method is called after all of its superclasses’ +load methods.

• A category +load method is called after the class’s own +load method.

In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.

So if you add a +load to, say, your app delegate class it will run before main().

HTH

Community
  • 1
  • 1
CRD
  • 52,522
  • 5
  • 70
  • 86
  • What about the metaclasses of weak-linked frameworks? – Boon Jun 02 '14 at 12:34
  • @Boon - any `+load` methods in a framework are executed when the framework is loaded by the dynamic linker, whenever (and if) that occurs. Weak-linking is orthogonal to this and enables an application to execute with or without a particular framework. – CRD Jun 02 '14 at 17:49
  • What I mean is the metaclass objects are probably instantiated as well, otherwise call such as [MPPlayableContentManager class] to check if the current OS version supports the API won't work. Is my guess correct? – Boon Jun 02 '14 at 19:03
  • @Boon - Consider the first bullet and the last para of the quote, do they imply a weak-linked framework will be loaded before your main image? Place a symbolic breakpoint on `load` and watch. – CRD Jun 02 '14 at 20:05