OBJECTIVE-C message and message forwarding mechanism
First, the basic concept
1. Method data structure in Objc_class
typedef struct OBJC_METHOD *method;
typedef struct OBJC_ Method {
SEL method_name;
Char *method_types;
IMP Method_imp;
};
2. SEL
typedef struct OBJC_SELECTOR *sel;
It is a pointer to the Objc_selector that represents the name/signature of the method.
3. IMP
typedef ID (*IMP) (ID, SEL, ...);
The IMP is a function pointer that contains an object ID (self pointer) that receives the message, an optional SEL (method name) for the calling method, and an indeterminate number of method parameters, and returns an ID
Second, the mechanism of message invocation
The compiler converts the message into a call to the message function objc_msgsend, which does everything it needs to do dynamic binding:
1, it first finds the SEL corresponding method to implement IMP. Because different classes may have different implementations for the same method, the method implementations found depend on the type of the message receiver.
2, then pass the message receiver object (pointer to the message receiver object) and the parameters specified in the method to the method implementation IMP.
3, finally, the return value of the method implementation is returned as the return value of the function.
Third, the process of finding imp according to SEL
1, first go to the class Objc_class method cache to find, if found, return it;
2, if not found, go to the list of methods in the class to find. If found in the method list of the class, the IMP is returned and cached in the cache.
3, if the corresponding IMP is not found in the method list of the class, the Super_class pointer in the class structure is searched in the method list of its parent class structure until the corresponding IMP is found in the method list of a parent class, returned to it, and added to the cache;
4, if the corresponding IMP is not found in the list of methods for itself and all the parent classes, then the message forwarding mechanism is entered
OBJECTIVE-C mechanism for message invocation