目前我把它理解为一种“空对象”。但它到底是什么呢?
发布于 2009-12-04 05:26:26
Objective-C对象
首先,当你调用这个的时候:
id someObject = [NSArray array];someObject不是直接的数组对象,只是指向数组对象的指针。也就是说,如果someObject等于0x1234,那么在内存的那个地址上就有一个对象。
这就是为什么
id someOtherObject = someObject;不复制对象。现在,两个指针都指向同一个对象。
指向0x0的指针
那么,nil是如何定义的呢?让我们来看一下源代码:
objc.h
#define nil __DARWIN_NULL /* id of Nil instance */_types.h
#ifdef __cplusplus
…
#else /* ! __cplusplus */
#define __DARWIN_NULL ((void *)0)
#endif /* __cplusplus */看起来nil是指向地址0x0的指针。
那又怎么样?
让我们看看Objective-C Programming Reference有什么要说的:
将消息发送到nil
在Objective-C中,向nil发送消息是有效的-它在运行时根本不起作用。Cocoa中有几种模式利用了这一事实。从消息返回到nil的值也可能是有效的:…
返回值为nil、0或所有变量均初始化为0的struct。它是哪一个取决于预期的返回类型。对于发送到nil的消息,objective-c运行时中有一个显式检查,这意味着它真的很快。
Nil、nil、NULL
这是三种类型。下面是所有的定义:
#define Nil __DARWIN_NULL /* id of Nil class */
#define nil __DARWIN_NULL /* id of Nil instance */
#define NULL __DARWIN_NULL
#define __DARWIN_NULL ((void *)0)可以看出,它们都是完全相同的。Nil和nil是由Objective-C定义的,NULL来自于C。
那有什么区别呢?这只是风格的问题。它使代码更具可读性。
Nil用作不存在的类:Class someClass = Nil.nil用作不存在的实例:id someInstance = nil.NULL是指向不存在的内存部分的指针:char *theString = NULL.短的
nil不是空对象,而是一个不存在的对象。如果空对象不存在,则方法-getSomeObject不会返回空对象,而是返回nil,这会告诉用户没有对象。
也许这是有意义的:(两者都可以编译和运行。)
if (anObject == nil) { // One cannot compare nothing to nothing,
// that wouldn't make sense.
if (anObject) { // Correct, one checks for the existence of anObject发布于 2009-12-04 02:44:42
它不是一个空对象,而是缺少任何对象。其余的答案涵盖了其他语义,所以我就到此为止:)
发布于 2009-12-04 02:43:46
nil只能与指针一起使用,nil表示指向nothing (它的值为零)的指针
NSString *myString = nil; // myString points to nothing
int x = nil; // invalid, "x" is not a pointer, but it will compilehttps://stackoverflow.com/questions/1841983
复制相似问题