nil
- nil 是 ObjC 对象的字面空值,对应 id 类型的对象,或者使用 @interface 声明的 ObjC 对象。
- 例如:
NSString *someString = nil;
NSURL *someURL = nil;
id someObject = nil;
if (anotherObject == nil)
|
- 定义:
#ifndef nil
# if __has_feature(cxx_nullptr)
# define nil nullptr
# else
# define nil __DARWIN_NULL
# endif
#endif
#define __DARWIN_NULL ((void *)0)
|
Nil
- Nil 是 ObjC 类类型的书面空值,对应 Class 类型对象。
- 例如:
Class someClass = Nil;
Class anotherClass = [NSString class ];
|
- 定义声明和 nil 是差不多的,值相同:
#ifndef Nil
# if __has_feature(cxx_nullptr)
# define Nil nullptr
# else
# define Nil __DARWIN_NULL
# endif
#endif
|
NULL
- NULL 是任意的 C 指针空值。
- 例如:
int *pointerToInt = NULL;
char *pointerToChar = NULL;
struct TreeNode *rootNode = NULL;
|
- 定义:
NSNull
- NSNull 是一个代表空值的类,是一个 ObjC 对象。实际上它只有一个单例方法:+[NSNull null],一般用于表示集合中值为空的对象。
- 例子说明:
NSArray *array = [NSArray arrayWithObjects:@ "one" , @ "two" , nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:nil forKey:@ "someKey" ];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNull null] forKey:@ "someKey" ];
|
- 定义:
#import <Foundation/NSObject.h>
@interface NSNull : NSObject <NSCopying, NSSecureCoding>
+ (NSNull *)null;
@end
|
NIL 或 NSNil
ObjC 不存在这两个符号!
小结
虽然 nil, Nil, NULL 的值相同,理解它们之间的书面意义才重要,让代码更加明确,增加可读性。