nil:指向一个对象的空指针,对objective c id 对象赋空值.

Nil:指向一个类的空指针,表示对类进行赋空值.

NULL:指向其他类型(如:基本类型、C类型)的空指针, 用于对非对象指针赋空值.

NSNull:在集合对象中,表示空值的对象.

1.nil 在指向一个对象的指针为空 定义如下:

#ifndef nil
# if __has_feature(cxx_nullptr)
# define nil nullptr
# else
# define nil __DARWIN_NULL
# endif
#endif

在Objective-C中用于id类型的对象

NSString *str = nil;
NSURL *url = nil;
id object = nil;

2.Nil 指向一个类的指针为空 定义如下:

#ifndef Nil
# if __has_feature(cxx_nullptr)
# define Nil nullptr
# else
# define Nil __DARWIN_NULL
# endif
#endif

在Objective-C中用于Class类型的对象

Class Class1 = Nil;
Clsss Class2 = [NSURL class];

3.NULL 指向C类型的指针为空 在stddef.h中定义如下:

#if defined(__need_NULL)
#undef NULL
#ifdef __cplusplus
# if !defined(__MINGW32__) && !defined(_MSC_VER)
# define NULL __null
# else
# define NULL 0
# endif
#else
# define NULL ((void*)0)
#endif

用于对非对象指针赋空值简单举例

int   *intA    = NULL;
char *charC = NULL;
struct structStr = NULL;

4.NSNull在Objective-C中是一个类.

NSNull有 + (NSNull *)null; 单例方法.

多用于集合(NSArray,NSDictionary)中值为空的对象.

NSArray *array = [NSArray arrayWithObjects:
[[NSObject alloc] init],
[NSNull null],
@"aaa",
nil,
[[NSObject alloc] init],
[[NSObject alloc] init], nil]; NSLog(@"%ld", array.count); // 输出 3,NSArray以nil结尾

//

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
@"Object0", @"Key0",
@"Object1", @"Key1",
nil, @"Key-nil"
@"Object2", @"Key2",
nil];
NSLog(@"%@", dictionary); // 输出2个key-value,NSDictionary也是以nil结尾

//

NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
[mutableDictionary setObject:nil forKey:@"Key-nil"]; // 会引起Crash
[mutableDictionary setObject:[NSNull null] forKey:@"Key-nil"]; // 不会引起Crash
//所以在使用时,如下方法是比较安全的
[mutableDictionary setObject:(nil == value ? [NSNull null] : value)
forKey:@"Key"];
文/Jasomzl(简书作者)
原文链接:http://www.jianshu.com/p/c01e875686d3
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

最新文章

  1. C#高级二
  2. BZOJ 1954 The xor-longest Path
  3. 【Modal】
  4. MVC中一般为什么用IQueryable而不是用IList
  5. jQuery模拟页面加载进度条
  6. USACO Preface Numbering 构造
  7. [ios2]Emoji表情符号兼容方案 【转】
  8. 【English】20190428
  9. BZOJ-3105: 新Nim游戏 (nim博弈&线性基)
  10. java第一次上机实验--验证码
  11. 04-MirrorGate安装脚本备注
  12. 配置中心Server端
  13. EasyUI Dialog 对话框 关闭事件
  14. 【Java初探实例篇01】——Java语言基础
  15. dp练习(3)——棋盘问题
  16. java之args[0]
  17. excel中如何将时间戳转换为日期格式
  18. 谈谈你对Java异常处理机制的理解
  19. ie debugger注册码
  20. Zabbix——设置阈值和报警

热门文章

  1. 判断浏览器类型用 document.documentMode方式,
  2. 探测FTP状态,socket方式
  3. Spring整理
  4. asp.net 重定向的三种方法
  5. GC
  6. 纯CSS实现下拉菜单及下拉容器等(纯CSS实现导航条及导航下拉容器)
  7. 《Linux内核设计与实现》CHAPTER17阅读梳理
  8. MVC+knocKout.js 实现下拉框级联
  9. 使用HTML5技术控制电脑或手机上的摄像头
  10. Python开发【十一章】:数据库操作Memcache、Redis