IOS self and super Detailed Explanation of Implementation Principle and Difference

  • 2021-08-17 01:14:40
  • OfStack

The difference between self and super

1. self calls its own method and super calls the parent class method
2. self is a class and super is a precompiled instruction
3. The outputs of "self class" and "super class" are 1 sample

Underlying Implementation Principle of self and super

1. When using self to call a method, it will start from the method list of the current class. If not, it will be found from the parent class; When using super, start from the list of methods of the parent class, and then call this method of the parent class.

2. When called using self, the objc_msgSend function is used: id objc_msgSend (id theReceiver, SEL theSelector,...). The first parameter is the message receiver, the second parameter is the selector of the concrete class method being called, followed by the variable parameter of the selector method. Taking [self setName:] as an example, the compiler will replace it with a function call that calls objc_msgSend, where theReceiver is self and theSelector is @ selector (setName:). This selector is setName found from the method list of class of the current self, and the corresponding selector is passed when it is found.

3. When called with super, the objc_msgSendSuper function is used: id objc_msgSendSuper (struct objc_super * super, SEL op,...) The first parameter is a structure of objc_super, and the second parameter is selector similar to the above class method.


struct objc_super {  
   id receiver;  
   Class superClass; 
}; 

When the compiler encounters [super setName:], start doing these things:

1) Construct the structure of objc_super. At this time, the first member variable receiver of this structure is the subclass, which is the same as self. The second member variable superClass means that the parent class calls the method of objc_msgSendSuper and passes this structure and sel of setName.

2) The function is doing something like this: Find selector of setName from the method list of superClass pointed by objc_super structure, and then use objc_super- > receiver to call this selector

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: