nil,NULL和[NSNULL nil]之间有什么区别? [英] What are the differences between nil, NULL and [NSNULL nil]?
问题描述
我收到这样的错误 - *由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:** - [NSCFDictionary initWithObjects:forKeys:count:]:尝试在对象[0]处插入nil值( key:搜索)'
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)'
然后我尝试了以下代码
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 is nil'。
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
是Objective-C版本的与应用于Obj-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为 aren'概念上相同的只是指针。因此为他们创建了一个特殊的哨兵。
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
stringify非常相似: nil
字符串为(null)
, NSNull
为< null>
。
Note that nil
and NSNull
stringify very similarly: nil
stringifies as (null)
, and NSNull
as <null>
.
这篇关于nil,NULL和[NSNULL nil]之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!