Understanding Objective‑C Categories: Implementation, Load and Initialize Mechanisms
This article explains the internal structure of Objective‑C categories, how they are represented as structs in the runtime, the process by which the Mach‑O loader discovers and attaches them, and the distinct execution order of their +load and +initialize methods.
Objective‑C categories provide a flexible way to extend existing classes without subclassing; they are implemented as a struct _category_t containing the category name, a pointer to the target class, and lists for instance methods, class methods, protocols and properties.
The runtime loads category data from the Mach‑O __DATA/__objc_catlist section. Functions such as _objc_init , _dyld_objc_notify_register , and load_images read this section, build internal tables, and invoke load_categories_nolock to attach each category to its class.
During attachment, attachCategories merges the category’s method, property and protocol lists into the class’s own lists, ensuring that later‑compiled categories appear earlier in the combined arrays, which influences method‑resolution order.
The +load method handling is performed after all classes are realized. prepare_load_methods collects class and category load functions into loadable_classes and loadable_categories . call_load_methods then executes class +load methods first, followed by category +load methods, repeating until no new loadable items appear.
+initialize is triggered the first time a class receives a message. The lookup path calls realizeAndInitializeIfNeeded_locked , which invokes initializeNonMetaClass recursively up the superclass chain before finally calling the class’s or category’s initialize implementation via objc_msgSend .
In summary, categories are lightweight struct‑based extensions whose loading order depends on compilation order, +load methods run before +initialize, and a category’s +initialize can override the original class’s implementation, while superclass initialization may be invoked multiple times for each subclass.
JD Retail Technology
Official platform of JD Retail Technology, delivering insightful R&D news and a deep look into the lives and work of technologists.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.