学科:Objective-C/nil
ObjC中的nil与C/C++中的NULL指针有很多相似之处,但有些值得注意的不同:
- nil不是标量,而是对象
- 可以向nil对象发送消息,如果消息的返回值是对象的话,运行时会返回nil。对此官方文档有这样的描述[1]:
In Objective-C, it is valid to send a message to a nil object. The Objective-C runtime assumes that the return value of a message sent to a nil object is nil, as long as the message returns an object or any integer scalar of size less than or equal to sizeof(void*). On Intel-based Macintosh computers, messages to a nil object always return 0.0 for methods whose return type is float, double, long double, or long long. Methods whose return value is a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, will return 0.0 for every field in the data structure. Other struct data types will not be filled with zeros. This is also true under Rosetta. On PowerPC Macintosh computers, the behavior is undefined.
譯文:在Objective-C中,向nil對象發送消息是有效的。 Objective-C運行時假定發送到nil對象的消息的返回值為nil,只要該消息返回一個對像或任何大小小於或等於sizeof(void *)的整數標量。 在基於Intel的Macintosh計算機上,對於返回類型為float,double,long double或long long的方法,對nil對象的消息始終返回0.0。 返回值為結構的方法(由Mac OS X ABI函數調用指南定義,將在寄存器中返回)將為數據結構中的每個字段返回0.0。 其他結構數據類型不會用零填充。 Rosetta也是如此。 在PowerPC Macintosh計算機上,行為未定義。
- Key-Value编程时,需要对nil特殊处理,见:Key-Value Coding Programming Guide > Handling nil Values