Geo*_*lly 33
首先,当你这样称呼时:
id someObject = [NSArray array];
Run Code Online (Sandbox Code Playgroud)
someObject不是直接的数组对象,而只是指向它的指针.这意味着,如果someObject等于0x1234存储器中该地址的对象.
这就是原因
id someOtherObject = someObject;
Run Code Online (Sandbox Code Playgroud)
不复制对象.两个指针现在指向同一个对象.
那么,如何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)
可以看出,它们完全相同.Nil和nil由目标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表示一个指向任何东西的指针(它的值为零)
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)
| 归档时间: |
|
| 查看次数: |
2805 次 |
| 最近记录: |