什么是最好的描述?真的是什么?

ope*_*rog 13 null cocoa cocoa-touch objective-c

目前我把它理解为一种"空对象".但究竟是什么呢?

Geo*_*lly 33

Objective-C对象

首先,当你这样称呼时:

id someObject = [NSArray array];
Run Code Online (Sandbox Code Playgroud)

someObject不是直接的数组对象,而只是指向它的指针.这意味着,如果someObject等于0x1234存储器中该地址的对象.

这就是原因

id someOtherObject = someObject;
Run Code Online (Sandbox Code Playgroud)

不复制对象.两个指针现在指向同一个对象.

指向0x0的指针

那么,如何nil定义?我们来看看源代码:

objc.h

#define nil __DARWIN_NULL    /* id of Nil instance */
Run Code Online (Sandbox Code Playgroud)

_types.h

#ifdef __cplusplus
…
#else /* ! __cplusplus */
#define __DARWIN_NULL ((void *)0)
#endif /* __cplusplus */
Run Code Online (Sandbox Code Playgroud)

看起来像是nil指向地址0x0的指针.

所以呢?

让我们看看Objective-C Programming Reference所说的内容:

发送消息为零

在Objective-C中,将消息发送到nil是有效的 - 它在运行时根本没有效果.Cocoa中有几种模式可以利用这一事实.从消息返回到nil的值也可能有效:...

返回值为nil0或a struct,所有变量初始化为0.它取决于预期的返回类型.对于消息来说,在objective-c运行时中有一个明确的检查nil,这意味着它真的很快.

Nil,nil,NULL

这是3种类型.以下是所有定义:

#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)
Run Code Online (Sandbox Code Playgroud)

可以看出,它们完全相同.Nilnil由目标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
Run Code Online (Sandbox Code Playgroud)

  • 将指针变量与`nil`进行比较是完全有效的.你甚至可能会认为它更明确地是一个"nil"检查,而不仅仅是指针作为真理表达式(尽管我自己使用了真值表达形式). (4认同)

Ste*_*ker 14

它不是一个空物体,它根本就缺乏任何物体.其余的答案涵盖了其他语义,所以我会留在那:)

  • 这是迄今为止最好的答案. (5认同)

Phi*_*ert 7

nil应该只用于指针,而nil表示一个指向任何东西的指针(它的值为零)

NSString *myString = nil; // myString points to nothing
int x = nil; // invalid, "x" is not a pointer, but it will compile
Run Code Online (Sandbox Code Playgroud)