iOS 为什么给nil发送消息不会崩溃?
2019-06-13 本文已影响0人
CrazyItCoder
我们知道 Objective-C 是以C语言为基础的,在C语言中对空指针进行操作会导致程序崩溃,为什么在 Objective-C 中给 nil 发送消息不会出现崩溃呢?
Objective-C中的函数调用都是通过objc_msgSend进行消息发送来实现的,而objc_msgSend会通过判断参数self来决定是否发送消息,如果传递给objc_msgSend的参数self为 nil,那么selector会被置空,该函数不会执行而是直接返回。
发送消息给nil
在Objective-C中,给nil发送消息是有效的-只在运行时不会起作用。Cocoa几个模式就利用了这一点。给nil发送消息的返回值也是有效的。
- 如果方法的返回值是对象,那给nil发送消息会返回0(
nil)。 - 如果方法的返回值是指针类型,其指针类型大小是小于等于
sizeof(void*),float,double,long double,long long,给nil发送消息将返回0。 - 如果方法的返回值为
struct(结构体),定义在OS X ABI Function Call Guide 里以寄存器形式返回的,那么给nil发送消息会返回的结构体中的各个字段都为0,其它结构体数据类型的就不会用0填充。 - 如果返回值不是上述描述的几种情况,给
nil发送消息返回值是undefined。
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 tonilmay 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 tonilreturns0.0for every field in thestruct. Otherstructdata 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.
想了解更多,请查阅官方文档。
注意⚠️
-
nil: 指向Objective-C中对象的空指针 -
Nil: 指向Objective-C中类的空指针 -
NULL:指向其他类型的空指针,如一个c类型的内存指针 -
NSNull:在集合对象中,表示空值的对象