nil、NULL 和 [NSNULL nil] 之间有什么区别? [英] What are the differences between nil, NULL and [NSNULL nil]?
问题描述
我遇到了这样的错误 -
I got an error like this -
由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:-[NSCFDictionaryinitWithObjects:forKeys:count:]: 尝试在objects[0] (key: searched)'
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"];
我收到了 NSLog 消息,因为Obj 为零".
And I got the NSLog message as 'Obj is nil'.
但是,当我在 Obj 是 NSString 并且我的应用程序因 nil 值而终止时使用上述相同的代码时,我收到了 NSLog 消息Obj is (id)[NSNull null]".
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]'.
nil、NULL 和 [NSNULL nil] 有什么区别?
是否有不同类型的 Null 值?如果是,如何共同检查这些空值?
谢谢:-)
推荐答案
NULL
是原始 C 风格的值,它被赋予一个指针,该指针被认为没有指向明确的地址.它通常仅用于表示未设置"或作为哨兵值.
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
是适用于 Obj-C 对象引用的同一事物的 Objective-C 版本:
nil
is the Objective-C version of the same thing as applied to Obj-C object references:
NSString * str = nil;
id foo = nil;
它们都被定义为等于零值,虽然您可以互换使用它们,但前者主要在 Obj-C 中用于传统指针(例如设置 void *
指向 NULL 的上下文指针)和 nil
用于所有 Obj-C 对象引用.
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.
之所以存在差异,是因为虽然 Obj-C 的语法恰好位于 C 之上,但该语言的设计是更高级别的,并且它的对象 ID 在概念上与指针"不同.因此,为他们创建了一个特殊的哨兵.
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]
是一个对象 旨在用于非常特定的情况(例如插入到集合中),其中需要非值"值,但实际 nil
是不允许的,必须使用一个对象.
[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.
请注意,nil
和 NSNull
字符串化非常相似:nil
字符串化为 (null)
和 NSNull
为
.
Note that nil
and NSNull
stringify very similarly: nil
stringifies as (null)
, and NSNull
as <null>
.
这篇关于nil、NULL 和 [NSNULL nil] 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!