ios 寻找一种优雅的方式来检查字典中是否存在密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11653110/
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
Looking for an elgant way to check if a Key exsists in a dictionary
提问by trojanfoe
Possible Duplicate:
How to check if an NSDictionary or NSMutableDictionary contains a key?
I can get the an array of the Keys (strings) from the dictionary then loop through it doing a string compare with the Key i want to check for and see if that dictionary contains the key I seek.
我可以从字典中获取键(字符串)数组,然后循环遍历它,将字符串与我要检查的键进行比较,看看该字典是否包含我要查找的键。
But is there a more elegant want to check if the key exists in the dictionary?
但是有没有更优雅的方式想要检查字典中是否存在键?
NSArray * keys = [taglistDict allKeys];
for (NSString *key in keys)
{
// do string compare etc
}
-Code
-代码
回答by trojanfoe
An NSDictionary
cannot contain nil
values, so you can simply use [NSDictionary objectForKey:]
which will return nil
if the key does not exist:
AnNSDictionary
不能包含nil
值,因此您可以简单地使用[NSDictionary objectForKey:]
which 将nil
在键不存在时返回:
BOOL exists = [taglistDict objectForKey:key] != nil;
EDIT: As mentioned by @OMGPOP, this also works using Objective-C literals using the following syntax:
编辑:正如@OMGPOP 所提到的,这也适用于使用以下语法的 Objective-C 文字:
NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key3"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");
Prints:
印刷:
Does not exist
回答by Eric
Trojanfoe is likely better, but you could also do:
Trojanfoe 可能更好,但您也可以这样做:
[[taglistDict allKeys]containsObject:key]
回答by MrBr
Assuming the key is of type NSString
and keys
is a dictionary, then you should instead be using something like:
假设键是类型NSString
并且keys
是字典,那么您应该使用以下内容:
if [keys containObject:key] {
// do something
}