我正在为一个 iPhone 应用程序使用 objective c。
我看到了 [dictionary objectForKey:@"key"]
返回 <null>
.做一个if([dictionary objectForKey:@"key"] == nil || [dictionary objectForKey:@"key"] == null)
似乎没有捕获这种情况。
做 if([[dictionary objectForKey:@"key"] isEqualToString:@"<null>"])
导致我的程序崩溃。
捕捉的正确表达是什么<null>
?
更多详情 nil 的 if 语句仍然没有捕获这个案例......也许我太累了看不到东西,但这里有额外的信息:
字典通过包含 json 数据的 url 填充,如下所示:
NSURL *url = [NSURL URLWithString:"http://site.com/"];
dataresult = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:dataresult options:kNilOptions error:& error];
在字典上做一个 NSLog 给出这个输出:
{
key = "<null>";
responseMessage = "The email / registration code combination is incorrect";
}
最佳答案
你有一个 NSNull
的实例。实际上, 实例,因为它是一个单例。
Cocoa 集合不能包含 nil
,但如果您尝试访问不存在的内容,它们可能会返回 nil
。
但是,有时对于程序来说,在集合中存储一个意思为“无”的东西是有值(value)的。这就是 NSNull
的用途。
碰巧,JSON 可以表示空对象。因此,当将 JSON 转换为 Cocoa 集合时,这些空对象会被转换为 NSNull
对象。
当 Cocoa 使用“%@”说明符格式化字符串时,nil
值将被格式化为带括号的“(null)”。 NSNull
值将被格式化为带有尖括号的“
关于objective-c - 字典 objectforkey 的 if 语句 : @"key" when value is <null>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10874564/