ios Cocoa/Objective-C - 验证 NSDictionary 上是否存在密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13090843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cocoa/Objective-C - Verify if a key exist on a NSDictionary
提问by fabio santos
How do I verify if a key exists on a NSDictionary
?
如何验证密钥是否存在于NSDictionary
?
I know how to verify if it has some content, but I want to very if it is there, because it's dynamic and I have to prevent it. Like in some cases it could happen to have a key with the "name" and is value, but in another cases it could happen that this pair of value don't exists.
我知道如何验证它是否有一些内容,但我很想知道它是否存在,因为它是动态的,我必须阻止它。就像在某些情况下,它可能碰巧有一个带有“名称”和值的键,但在另一种情况下,这对值可能不存在。
回答by CRD
The simplest way is:
最简单的方法是:
[dictionary objectForKey:@"key"] != nil
as dictionaries return nil
for non-existant keys (and you cannot therefore store a nil in a dictionary, for that you use NSNull
).
因为字典返回nil
不存在的键(因此您不能在字典中存储 nil,因为您使用NSNull
)。
Edit: Answer to comment on Bradley's answer
编辑:回答评论布拉德利的回答
You further ask:
你进一步问:
Is there a way to verify if this: [[[contactDetailsDictionary objectForKey:@"professional"] objectForKey:@"CurrentJob"] objectForKey:@"Role"] exists? Not a single key, because is a really giant dictionary, so it could exist in another category.
有没有办法验证: [[[contactDetailsDictionary objectForKey:@"professional"] objectForKey:@"CurrentJob"] objectForKey:@"Role"] 是否存在?不是一个键,因为它是一个非常巨大的字典,所以它可以存在于另一个类别中。
In Objective-C you can send a message to nil
, it is not an error and returns nil
, so expanding the simple method above you just write:
在 Objective-C 中,你可以向 发送消息nil
,它不是错误并返回nil
,所以扩展上面的简单方法你只需写:
[[[contactDetailsDictionary objectForKey:@"professional"]
objectForKey:@"CurrentJob"]
objectForKey:@"Role"] != nil
as if any part of the key-sequence doesn't exist the LHS returns nil
好像关键序列的任何部分不存在 LHS 返回 nil
回答by Bradley M Handy
NSDictionary
returns all of the keys as an NSArray
and then use containsObject
on the array.
NSDictionary
将所有键作为 an 返回NSArray
,然后containsObject
在数组上使用。
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"object", @"key"];
if ([[dictionary allKeys] containsObject:@"key"]) {
NSLog(@"'key' exists.");
}