一些关于[NSNull null]的混乱,没有 [英] some confusions about [NSNull null],nil

查看:95
本文介绍了一些关于[NSNull null]的混乱,没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

[NSNull null]和nil之间有什么区别?






1。

  id dicValue = aDictionary objetForKey:@aKey]; 

if(dicValue!= nil)
{
blablala ...
}



2。

  if(dicValue!= [NSNull null])
{
blablala ...
}

我应该选择第一个还是第二个?



或当它是这样:



3。

  if([aDictionary objetForKey:@aKey]!= nil )



p>

  if([aDictionary objetForKey:@aKey]!= [NSNull null])



又是什么?



1.2.3.4。这是正确的和推荐的?

解决方案

直接从 Apple文档

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

现在很清楚吗


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...
}

or

2.

if(dicValue != [NSNull null]) 
{
     blablala...
}

should I choose the first one,or the second one?

or when it comes like this :

3.

if ([aDictionary objetForKey:@"aKey"] != nil)

or

4.

if ([aDictionary objetForKey:@"aKey"] != [NSNull null])

and what again ?

1.2.3.4. which is correct and recommended?

解决方案

Directly from Apple Documentation.
The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).

NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = [NSArray arrayWithObject:nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
// output: "arrayWithNull: (<null>)"

It is important to appreciate that the NSNull instance is semantically different from NO or false—these both represent a logical value; the NSNull instance represents the absence of a value. The NSNull instance is semantically equivalent to nil, however it is also important to appreciate that it is not equal to nil. To test for a null object value, you must therefore make a direct object comparison.

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"

Is it clear now??

这篇关于一些关于[NSNull null]的混乱,没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆