Possible Duplicate:
What's the difference between [NSNull null] and nil?
What are the differences between nil, NULL and [NSNULL nil]?
1.
id dicValue = [aDictionary objetForKey:@"aKey"];
if(dicValue != nil)
{
blablala...
}
或
2.
if(dicValue != [NSNull null])
{
blablala...
}
我应该选择第一个还是第二个?
或者当它像这样出现时:
3.
if ([aDictionary objetForKey:@"aKey"] != nil)
或
4.
if ([aDictionary objetForKey:@"aKey"] != [NSNull null])
又是什么?
1.2.3.4。哪个是正确的和推荐的?
直接来自 Apple Documentation .
NSNull 类定义了一个单例对象,用于在禁止 nil 作为值的情况下(通常在数组或字典等集合对象中)表示空值。
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = [NSArray arrayWithObject:nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
// output: "arrayWithNull: (<null>)"
重要的是要认识到 NSNull 实例在语义上不同于 NO 或 false——它们都代表一个逻辑值; NSNull 实例表示没有值。 NSNull 实例在语义上等同于 nil,但是理解它不等于 nil 也很重要。因此,要测试空对象值,您必须进行直接对象比较。
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");
}
}
// output: "equals NSNull instance"
现在清楚了吗??