We all know that OC is a dynamic language, and the object invocation method is called to send a message to an object, for example:
ID returnvalue = [someobject messagename:parameter];
Someobject is called "receiver", MessageName is called "selector" (selector), and the selector and subsequent parameters are called "Messages". So what does the compiler do when it sees this information? OC as a superset of C language, at the bottom of all the methods are C language functions, we first see how the C language is the function call.
The C language uses "static binding", at compile time, the compiler can determine the function that the runtime should call, for example:
#import <stdio.h>
void Printhello ()
{
printf ("hello\n");
}
void Printbye ()
{
printf ("bye\n");
}
void fun (int type)
{
if (type = = 0)
{
Printhello ();
}
else
{
printbye ();
}
}
If "inline" is not considered, the compiler already knows the two functions Printhello and Printbye in the program when compiling the code, and then directly generates the instructions that invoke the functions. If you want to use "dynamic binding" to write the above code, how to do it. As follows:
#import <stdio.h>
void Printhello ()
{
printf ("hello\n");
}
void Printbye ()
{
printf ("bye\n");
}
void fun (int type)
{
void (*f) ();
if (type = = 0)
{
f = printhello;
}
else
{
f = printbye;
}
f ();
}
Using the function pointer, the function to be called will not be determined until the runtime. Back to OC
ID returnvalue = [someobject messagename:parameter];
The compiler converts this statement into a standard C-language function call:
ID returnvalue = Objc_msgsend (Someobject, @selector (messagename:), parameter);
The Objc_msgsend () function is the core of the OC Messaging mechanism, and its prototype is as follows:
void Objc_msgsend (id self, SEL cmd, ...)
This is a function with a variable number of parameters, the first argument represents the receiver, the second parameter represents the selector, and the following argument is the parameter passed in the message, and the Objc_msgsend function first searches for a list of methods in the class to which the recipient belongs, and jumps to its implementation code if it finds a method that matches the name of the selector If you can't find it, go up the inheritance system and find the right way to jump, and if you don't find a consistent method, then you'll perform a message forwarding operation. The message forwarding process is followed by a table ...