Search code examples
objective-clazy-evaluationobjective-c-runtime

Objective-C: What is a lazy class?


Looking at the Objective-C runtime library source code, particularly at objc-runtime-new.mm, I saw some functions and even comments which referred to lazy and non-lazy classes. It seems that classes that don't have a +load method are called lazy classes, but I'm not sure of that and most likely that is not right. After searching on Google, I didn't found anything about lazy classes on Objective-C.

So, what is a lazy class in Objective-C? Does Obj-C have this feature? Is it related to the presence of a +load method in a class' implementation? At the file linked above, the runtime system calls a function called _getObjc2NonlazyClassList in order to get a list of non-lazy classes from an image. Why isn't there a _getObjc2LazyClassList function too?


Solution

  • I found the answer: It's all about a class implementing or not a +load method.

    All the classes implemented in a given image file have a reference in a list stored in the "__DATA, __objc_classlist, regular, no_dead_strip" binary's section. This list allows the runtime system to keep track of all the classes stored in such file. However, not all of the classes need to be realized when the program starts up. That's why when a class implements a +load method, it also has a reference in a list stored in the "__DATA, __objc_nlclslist, regular, no_dead_strip" section.

    So, _getObjc2NonlazyClassList retrieves the list of classes that do implement a +load method and are so called non-lazy. _getObjc2ClassList retrieves a list of all the classes in a image file, including the classes that don't have a +load method (and are called lazy) and the non-lazy ones. Non-lazy classes must be realized when the program starts up. Lazy classes, on the other hand, don't need to be realized immediately. This may be delayed until the class receives a message for the first time, for example (that's the reason for them to be considered "lazy").

    The same is true for categories, by the way.