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 :-)
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)
来源:https://stackoverflow.com/questions/6814427/what-are-the-differences-between-nil-null-and-nsnull-nil