I think, whether you are a pure console program or a fancy UI application, you must compile according to the guidelines of the apple compiler and execute them according to the runtime rules of apple.
A program sends a message to a class or its instance object. Furthermore, a base class pointer to a derived class object may point to different derived class objects at different times. These derived classes may all define methods with the same method name. At this time, will this generic pointer know the method of the class to be executed?
The answer is that the message mechanism of objc helps you implement it.
Prerequisites:
1. All object-C objects know their classes. During compilation, the compiler adds an instance variable ISA to each object. The pointer variable is of the Class Object struct structure, which contains all information about the class. Note that the compiler only adds a pointer variable without a value assignment. The value assignment is done at runtime.
2. In the compilation phase, convert the methods defined in the class into C functions. The compiler will add two additional parameters in C language function parameters: Self and _ cmd. Self is the pointer to the Message Receiver; _ CMD is the method selector corresponding to the message.
3. At the start of running, the C function in the runtime creates class objects (actually a structure) for each nsobject class ). As mentioned above, this structure contains all information about the class. It should naturally contain methods defined in the class and store them in lists. Each record in the list corresponds to a method in the class, which has a "selector" field and a "function pointer" field. Now, you can use the selector to find the function to be executed.
Mechanism:
Shape * shape = [[shape alloc] init];
[Shape drawwithrect: rect];
When the compiler encounters the above message expression, use the objc_msgsend function in runtime to replace:
Objc_msgsend (shape, @ selector (drawwithrect :), rect );
Execute the objc_msgsend function call at runtime
1. objc_msgsend searches for the shape ISA variable and finds its corresponding class object through this pointer.
2. objc_msgsend: Check the cache of class objects and whether the function pointer can be quickly found.
3. If the function pointer is not in the cache, view the method list of the Class Object and find the function pointer.
4. Run the function after finding it.
The class object structure contains a pointer to the class object of its parent class. If the function pointer is not found in the class object, search again in the Class Object of the parent class until it is found or no error is reported.