iOS 深度好文

iOS 为什么给nil发送消息不会崩溃?

2019-06-13  本文已影响0人  CrazyItCoder

我们知道 Objective-C 是以C语言为基础的,在C语言中对空指针进行操作会导致程序崩溃,为什么在 Objective-C 中给 nil 发送消息不会出现崩溃呢?

Objective-C中的函数调用都是通过objc_msgSend进行消息发送来实现的,而objc_msgSend会通过判断参数self来决定是否发送消息,如果传递给objc_msgSend的参数selfnil,那么selector会被置空,该函数不会执行而是直接返回。

发送消息给nil

Objective-C中,给nil发送消息是有效的-只在运行时不会起作用。Cocoa几个模式就利用了这一点。给nil发送消息的返回值也是有效的。

Sending Messages to nil

In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:

  • If the method returns an object, then a message sent to nil returns 0 (nil).
  • If the method returns any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.
  • If the method returns a struct, as defined by the OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the struct. Other struct data types will not be filled with zeros.
  • If the method returns anything other than the aforementioned value types, the return value of a message sent to nil is undefined.

想了解更多,请查阅官方文档

注意⚠️
上一篇下一篇

猜你喜欢

热点阅读