objective-c - 什么最能描述零?那到底是什么?

标签 objective-c cocoa cocoa-touch null

目前我理解为一种“空对象”。但它到底是什么?

最佳答案

Objective-C 对象

首先,当你调用它时:

id someObject = [NSArray array];

someObject 不是直接的数组对象,而只是指向它的指针。这意味着,如果 someObject 等于 0x1234,则内存中该地址处有一个对象。

这就是原因

id someOtherObject = someObject;

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

指向0x0的指针

那么,nil是怎么定义的呢?我们来看一下源码:

对象.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 是什么不得不说:

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: …

返回值是nil、0 或所有变量都初始化为0 的struct。具体是哪一个取决于预期的返回类型。在 objective-c 运行时中有一个显式检查消息到 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)

可以看出,它们都是完全一样的。 Nilnil 由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

关于objective-c - 什么最能描述零?那到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841983/

相关文章:

cocoa - 何时创建自定义 NSNotificationCenter?

cocoa - 如何使用自动布局动态添加 nsslider 来查看

iphone - 将表格 View 单元格滚动出 View 时,单元格文本会更改

ios - iOS 是否支持 TLS 压缩?

ios - 不隐藏在键盘下方的文本字段动画,在 IOS 7 中的模拟和实际设备中表现不同

ios - IPv6 Apple 更新

ios - 如何在 IOS 中使用 UIView 打开 PDF 文件

python - 在Python中转换Cocoa时间戳

iphone - iPhone 应用程序中的 UIWindow 是在哪里实例化的?

ios - UINavigationController 弹出一个 View