NULL和nil是否等效? [英] Are NULL and nil equivalent?
问题描述
实际上我的问题是:null
和nil
是否相等?
Actually my question here is: are null
and nil
equivalent or not?
我有一个例子,但是当它们相等时我会感到困惑.
I have an example but I am confused when they are equal when they are not.
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = [NSArray arrayWithObject:nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
NSLog(@"equals nil");
} else if (aValue == [NSNull null]) {
NSLog(@"equals NSNull instance");
if ([aValue isEqual:nil]) {
NSLog(@"isEqual:nil");
}
}
在上述情况下,它表明null
和nil
都不相等,并且显示等于NSNull实例"
Here in the above case it shows that both null
and nil
are not equal and it displays "equals NSNull instance"
NSString *str=NULL;
id str1=nil;
if(str1 == str)
{
printf("\n IS EQUAL........");
}
else
{
printf("\n NOT EQUAL........");
}
在第二种情况下,它显示两者相等,并且显示"IS EQUAL".
And in the second case it shows both are equal and it displays "IS EQUAL".
任何人的帮助将不胜感激.
Anyone's help will be much appreciated.
谢谢你, 结束.
推荐答案
nil
和NULL
本质上是相同的,nil
类似于(NSObject *)0
,而NULL
更像是(void *)0
.但是两个都是整数值为零的指针.您可以将邮件发送到nil
而不会引发错误.
nil
and NULL
are essentially the same, nil
is something like (NSObject *)0
, while NULL
is more like (void *)0
. But both are pointers with an integer value of zero. You can send messages to nil
without raising an error.
NSNull
和NULL
(当然是nil
)是不同的.您只能将NSNull
用作帮助程序,以将empty
对象添加到NSArray
或另一个容器类中,因为您不能将nil
添加到它们中.因此,取而代之的是,使用[NSNull null]
作为替换,并且必须检查数组元素是否为NSNull
,而不是它是否为nil
(它永远不会等于nil
).
NSNull
and NULL
(or nil
, of course) are different things, however. You just use NSNull
as a helper to add an empty
object to an NSArray
or another container class, since you can't add nil
to them. So instead, you use [NSNull null]
as a replacement, and you have to check if an array element is NSNull
, not if it's nil
(it will never be equal to nil
).
这篇关于NULL和nil是否等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!