We know that the message sending program to nil in Objective-C will not crash,
Objective-C is based on the C language,
On PC, null pointer operations are performed in C language,
The program crashes due to a protection error due to out-of-bounds access,
But why won't Objective-C crash?
The reason must be found in the source code,
The following is the arm assembly code snippet of objc_msgSend:
In the arm function call process,
Generally, parameters are transmitted by r0-r4,
Use r0 to pass the returned value.
Corresponding to objc_msgSend. The first parameter is self, and the returned value is self, which is put in r0 (a1.
/*************************************** *****************************
* Idobjc_msgSend (idself, SELop ,...)
* On entry:A1 is the message sender er,
*A2 is the selector
**************************************** ****************************/
ENTRY objc_msgSend
# Check whether receiver is nil
Teq a1, #0
Moveq a2, #0
Bxeq lr
Teq instructions:
TEQ
R
n
,Operand2
The TEQ instruction performs a bitwise Exclusive OR operation on the value in Rn and the value of Operand2.
Test whether self is empty.
Moveq instructions:
If self is empty, the selector is also set to null.
Bx instructions:
In arm, bx lr is used to return to the place where the subroutine is called (that is, return to the caller). If self is empty, it is returned to the place where objc_msgSend is called for further execution.
In short:
If the self parameter passed to objc_msgSend is nil, this function will not perform meaningful operations and will return directly.