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

拜拜、爱过 提交于 2019-11-26 21:21:26

问题


I got an error like this - * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: **-[NSCFDictionary initWithObjects:forKeys:count:]: attempt to insert nil value at objects[0] (key: searched)'

Then I tried the below code

    if (Obj == (id)[NSNull null])  //Obj is an id 
{
    NSLog(@" Obj is (id)[NSNull null]");    
}
else if (Obj == nil)
{
    NSLog(@"Obj is nil");   
} 
else if (Obj == NULL)
{
    NSLog(@"Obj is NULL");  
} 
else
{
    NSLog(@"Obj is something else");
}

searchedDict = [NSDictionary dictionaryWithObject:Obj forKey:@"searched"];

And I got the NSLog message as 'Obj is nil'.

But when I used the same above code when Obj was NSString and my app got terminated due to nil value, I got the NSLog message as 'Obj is (id)[NSNull null]'.

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

Are there different kinds of Null values? if yes, How to check commonly for these null values?

Thanks :-)


回答1:


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>.




回答2:


[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.




回答3:


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)



来源:https://stackoverflow.com/questions/6814427/what-are-the-differences-between-nil-null-and-nsnull-nil

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