valueForKey 返回 nil

Jas*_*son 2 objective-c nsdictionary ios

愚蠢的问题警告......我可能会被剥夺睡眠,但我似乎无法弄清楚这一点。

“当前”是一个 NSDictionary

if ([current valueForKey:@"name"] != nil)
{
    NSLog(@"here %@", [current valueForKey:@"name"]);
}
Run Code Online (Sandbox Code Playgroud)

这打印

here John
here Sam
here <null>
here <null>
here Billy
Run Code Online (Sandbox Code Playgroud)

'if xx != nil' 不应该阻止空值吗?'name' 存在于我的字典中,但 name 的值可能为空。

Dha*_*ngh 5

NSArray并且NSDictionary不能包含 nil 值。NSNULL是专门作为 nil 的占位符创建的。可以放入集合类,只占空间。

NSNull定义了一个单例对象,这意味着它只有一个实例,NSNull但它可以在任意多的地方使用。

你需要像这样检查......

if (current != nil || [current valueForKey:@"name"] != [NSNull null] )
{
      NSLog(@"here %@", [current valueForKey:@"name"]);
}
Run Code Online (Sandbox Code Playgroud)

我相信你会得到这个输出.....

输出

here John
here Sam
here Billy
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但不应该是 &amp;&amp; 而不是 || ? 没有与 || 一起工作,但似乎与 &amp;&amp; 一起工作 (2认同)