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

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

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

发送消息给nil

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

  • 如果方法的返回值是对象,那给nil发送消息会返回0(nil)。
  • 如果方法的返回值是指针类型,其指针类型大小是小于等于 sizeof(void*)floatdoublelong doublelong 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 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.

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

注意⚠️
  • nil : 指向 Objective-C 中对象的空指针
  • Nil : 指向 Objective-C 中类的空指针
  • NULL :指向其他类型的空指针,如一个c类型的内存指针
  • NSNull :在集合对象中,表示空值的对象
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,759评论 0 38
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,907评论 1 32
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,559评论 0 23
  • 飘摇的旗子 云幡猎猎 古旧的庙宇 乡村的祭台 时断时续的鼓声 熙攘的人群哼鸣 传唱风俗的陈腔 悠长老去的调子 烟火...
    营州布衣阅读 1,180评论 1 11

友情链接更多精彩内容