What are the differences between nil, NULL and [NSNULL nil]?

独自空忆成欢 提交于 2019-11-27 23:08:33
Ben Zotto

NULL is the original C-style value given to a pointer which is deemed to point to no explicit address. It's generally just used to mean "unset" or as a sentinel value.

char * oldstring = NULL;

nil is the Objective-C version of the same thing as applied to Obj-C object references:

NSString * str = nil;
id foo = nil;

They are both defined to be equal to the value zero, and although you could use them interchangeably, the former is seen mainly within Obj-C for traditional pointers (like setting void * context pointers to NULL) and nil is used for all Obj-C object references.

The difference exists because although Obj-C's syntax happens to ride on top of C's, the design of the language is higher-level, and its object IDs aren't conceptually the same as just "pointers". Hence the creation of a special sentinel for them.

[NSNull null] is an object that is intended to be uses in very certain cases (like inserting into collections) where an "non-value" value is desired, but actual nil is not allowed, and an object must be used.

Note that nil and NSNull stringify very similarly: nil stringifies as (null), and NSNull as <null>.

[NSNull null] is a wrapper for the nil value you want to insert in the collection, if it is what you want.

NSNull class reference.

You can also check before if an object reference is nil simply with ==.

Also nil is defined as : #define nil NULL and is Objective C equivalent for C NULL.

Nil is for object pointers

NULL is for non pointers

[NSNULL null] is an object to represent "nil" to be used in cases that nil values are not allowed (as pointed out by Vince, like in collections e.g. NSArray and NSDictionary)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!