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?
-
I think it is same as C++ plus `+load` – Bryan Chen Jun 02 '14 at 04:53
-
2I'm curious why you're curious. What are you trying to accomplish? – CrimsonChris Jun 02 '14 at 04:59
-
1I could be wrong, but I always assumed that with Objective-C's dynamic nature that load/initialize get called 'just in time'. – Jasper Blues Jun 02 '14 at 05:29
-
@CrimsonChris I am trying to gain an understanding of things. – Boon Jun 02 '14 at 12:28
-
Three votes to close a question that's so clear and specific. Stop the madness. – Boon Jun 02 '14 at 13:04
-
1@JasperBlues load doesn't get called just in time - it's done before main. initialize possibly is JIT (during the first message sent to the class). – Boon Jun 02 '14 at 13:07
1 Answers
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
-
-
@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