为什么在 Objective-C 中给 nil 发送消息程序不会崩溃?

我们知道在 Objective-C 中给 nil 发送消息程序不会崩溃,

Objective-C 是以 C 语言为基础的,

PC 上,在 C 语言中对空指针进行操作,

程序会由于越界访问而出现保护错进而崩溃,

但是 Objective-C 中为什么不会崩溃呢?

原因需要从源代码中寻找,

下面是 objc_msgSend 的 arm 版汇编代码片段:

在 arm 的函数调用过程中,

一般用 r0-r4 传递参数,

用 r0 传递返回值。

对应 objc_msgSend,第一个参数为 self,返回值也是 self,都放在 r0(a1)中。

 

 

/********************************************************************

 * idobjc_msgSend(idself, SELop, ...)

 * On entry: a1 is the message receiver,

 *                  a2 is the selector

 ********************************************************************/

 

ENTRY objc_msgSend

# check whether receiver is nil

teq     a1, #0

moveq   a2, #0

bxeq    lr

 

teq 指令说明:

TEQ RnOperand2 The TEQ instruction performs a bitwise Exclusive OR operation on the value in Rn and the value of Operand2.

测试 self 是否为空。

moveq 指令说明:

如果self为空,则将 selector 也设置为空。

bx 指令说明:

在 arm 中 bx lr 用来返回到调用子程序的地方(即:返回到调用者),此处是:如果 self 为空,就返回到调用 objc_msgSend 的地方继续执行。

总之:

如果传递给 objc_msgSend 的 self 参数是 nil,该函数不会执行有意义的操作,直接返回。

posted @ 2012-12-17 23:20  Proteas  阅读(2526)  评论(3编辑  收藏  举报