检查是否包含Null

时间:2015-08-28 19:26:28

标签: ios objective-c

当我打印以下内容时,我得到(null)

NSLog(@"%@", [[responseObject objectAtIndex:i] objectForKey:@"child"]);

现在我想进行验证以检查它是否返回(null)。我该怎么做?

我尝试了以下但不起作用:

1

 if (![[[responseObject objectAtIndex:i] objectForKey:@"child"] isEqualToString:@"(null)"]) {

}

2

if (![[[responseObject objectAtIndex:i] objectForKey:@"child"]  isEqual:@"(null)"]) {
}

4 个答案:

答案 0 :(得分:2)

“null”不仅仅是NSString。您应该对null对象的概念进行一些研究。

您正在寻找的内容可以这样写:

if (![[responseObject objectAtIndex:i] objectForKey:@"child"]) {
    //key "child" not in dictionary
}

答案 1 :(得分:2)

(null)nil显示的NSLog的表示形式。

您可以写下以下内容:

if ([[responseObject objectAtIndex:i] objectForKey:@"child"] == nil) {

}

或者更短的选择:

if (![[responseObject objectAtIndex:i] objectForKey:@"child"]) {

}

答案 2 :(得分:0)

另一种检查方法是使用字符串长度。我知道其他答案也同样好,我只是给OP以及其他任何人提供更多选择。

NSString *childStr = [[responseObject objectAtIndex:i]objectForKey:@"child"];

if ([childStr length] < 1)
{
  //no value specified - childStr is NULL
}
else
{ 
 //there is something in the childStr - throw a party!
}

答案 3 :(得分:-1)

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"hello"]) {
  NSLog(@"only if not null show %@",[defaults objectForKey:@"hello"]);
}

这是一种从用户默认值中检查它的方法。只有在保存的对象不等于null时才会打印。