What are +load and +initialize, and which can Swift use?
Predict first
Which of these runs lazily, just before the first message to the class?
// A: +load
// B: +initialize
- A
- B
Mental model. +load is a sound check before the show, whether or not that act performs. +initialize is the warm-up that runs the first time the act is called to the stage.
Both are class methods the runtime calls for you, at different times. +load runs once per class and per category as the binary’s image is loaded, before main, whether or not you ever use the class. It was the classic hook for method swizzling and for registering categories. +initialize runs lazily, just before the first message is sent to the class (or a subclass), once per class, and can be inherited, so a subclass that does not override it may trigger the superclass version again.
Swift gave up both. You cannot override +load in Swift, and overriding initialize() was removed, partly because running arbitrary code at load time slows launch and makes order unpredictable. Swift-side replacements are explicit: a lazily initialised static let (which is thread-safe and runs once), or an explicit setUp() call during app launch. In mixed code an Objective-C +load in a legacy file still runs, and is a common source of launch-time cost.
+initialize is lazy. +load runs eagerly at image load, whether or not the class is used.
Common traps
- Doing heavy work in
+load. It runs for every class on every launch and delays the first frame. - Assuming
+initializeruns only for the declaring class. A subclass without its own can trigger the superclass copy again; guard with a check onself.
They might follow up with
- How does Swift get one-time setup?
static letproperties are initialised lazily and exactly once, and globals the same way. - Why was swizzling usually in
+load? It runs early and once, before other code can call the method.
Related questions
- 4.6.1 How does method swizzling work, and why does it need dynamic in Swift?
- 4.1.4 What is isa, and why does your object’s runtime class sometimes differ from its Swift type?
← What are associated objects, and when are they the right (or wrong)…