当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS中nil、Nil、NULL、NSNull详解

iOS中nil、Nil、NULL、NSNull详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

德惠二手房信息,玉观音下载,喜临门床垫

objc 里面的几个空值符号经常会差点把我搞死,这些基础的东西一点要弄清楚才行,以提高码农的基本素质。

nil

nil 是 objc 对象的字面空值,对应 id 类型的对象,或者使用 @interface 声明的 objc 对象。
例如:

nsstring *somestring = nil;
nsurl *someurl = nil;
id someobject = nil;
if (anotherobject == nil) // do something

定义:

// objc.h
#ifndef nil
# if __has_feature(cxx_nullptr)
#  define nil nullptr
# else
#  define nil __darwin_null
# endif
#endif
 
// __darwin_null in _types.h
 
#define __darwin_null ((void *)0)

nil

nil 是 objc 类类型的书面空值,对应 class 类型对象。
例如:

class someclass = nil;
class anotherclass = [nsstring class];
定义声明和 nil 是差不多的,值相同:

// objc.h
#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;

定义:

// in stddef.h 
#define null ((void*)0)

nsnull

nsnull 是一个代表空值的类,是一个 objc 对象。实际上它只有一个单例方法:+[nsnull null],一般用于表示集合中值为空的对象。
例子说明:

// 因为 nil 被用来用为集合结束的标志,所以 nil 不能存储在 foundation 集合里。
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"];
定义:

/* nsnull.h
  copyright (c) 1994-2012, apple inc. all rights reserved.
*/
#import <foundation/nsobject.h>
@interface nsnull : nsobject <nscopying, nssecurecoding>
+ (nsnull *)null;
@end

小结

虽然 nil, nil, null 的值相同,理解它们之间的书面意义才重要,让代码更加明确,增加可读性。

以上所述就是本文的全部内容了,希望大家能够喜欢。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网