In the past two weeks, in order to complete a job, I have been exposed to the very special two class method in NSObject. What makes them special is that iOS runs ahead of time and automatically calls both methods, and many of the Rules for class methods (such as inheritance, category) are handled differently.
And because these two methods are called at the beginning of the program's run, we can use them to do some preprocessing before the class is used. For example, what I came across was to have the class automatically save its class name to a nsdictionary.
Let's take a look at the two methods described in NSObject Class reference:
+ (void) initialize
The runtime sends initialize to each class-a program exactly one time just before the class, or any class that inherits from It, is sent their first message from within the program. (Thus the method never be invoked if the class was not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
+ (void) load
loadthe message is sent to classes and categories that's both dynamically loaded and statically linked, but only if th E newly loaded class or category implements a method that can respond.
The order of initialization is as follows:
- All initializers in the any framework of you link to.
- All
+load methods in your image.
- All C + + static initializers and C + +
__attribute__(constructor) functions in your image.
- All initializers in frameworks so link to you.
In addition:
- A class ' s method is called after all of its
+load superclasses ' +load methods.
- A Category
+load method is called after the class ' s own +load method.
In a custom implementation load of your can therefore safely message other unrelated classes from the same image, and any loadmethods implemented by those classes could not have run yet.
Apple's documentation clearly shows that the difference between initialize and load is that load is called whenever a file of the class is referenced, and initialize is called before the first method of the class or its subclasses is called. So if the class is not referenced into the project, there will be no load call, but even if the class file is referenced but not used, then initialize will not be called.
Their similarities are that the method is only called once. (In fact, this is relative to the runtime, there will be further explanation behind).
The document also explicitly states the order of the method calls: The method of the parent class (superclass) takes precedence over the subclass (subclass) method, and the methods in the class take precedence over the methods in the category.
But there are many other places that are not explained in detail in the article. So look at some sample code to clarify the details that should be noted.
Objective C-class method load and Initialize differences