iphone - 关于[NSNull null],nil的一些困惑

标签 iphone objective-c cocoa

<分区>

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"

现在清楚了吗??

关于iphone - 关于[NSNull null],nil的一些困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121293/

相关文章:

objective-c - 当 ICScannerFunctionalUnit 设置为黑白扫描时,ImageCaptureCore 错误 -9933

swift - 如何通过代码在 SceneKit 中设置基于物理的渲染?

c# - 像在亚洲一样测试 iOS 应用程序

iphone - 如何防止 iPhone NSNumberFormatter 舍入?

iphone - Cocos2d 数组中的随机对象未被调用

objective-c - NSDictionary initWithObjectsAndKeys 是否处理 NULL/nil 对象和 NSString 对象以外的对象

ios - 值转换问题?

ios - NSURLSession 和代表

cocoa - 无法让简单的工具栏发挥作用!

iphone - 访问,从单个 Nib 获取对多个 View 的引用