【问题标题】:Looking for an elgant way to check if a Key exsists in a dictionary [duplicate]寻找一种优雅的方法来检查字典中是否存在密钥[重复]
【发布时间】:2012-07-25 15:22:05
【问题描述】:

可能重复:
How to check if an NSDictionary or NSMutableDictionary contains a key?

我可以从字典中获取键(字符串)的数组,然后循环遍历它,与我要检查的键进行字符串比较,看看该字典是否包含我寻找的键。

但是有没有更优雅的方法来检查字典中是否存在键?

        NSArray * keys = [taglistDict allKeys];
        for (NSString *key in keys) 
        {
           // do string compare etc
        }

-代码

【问题讨论】:

标签: iphone objective-c ios ipad


【解决方案1】:

NSDictionary 不能包含 nil 值,因此您可以简单地使用 [NSDictionary objectForKey:],如果密钥不存在,它将返回 nil

BOOL exists = [taglistDict objectForKey:key] != nil;

编辑:正如@OMGPOP 所提到的,这也适用于使用以下语法的Objective-C 文字:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };

if (dict[@"key3"])
    NSLog(@"Exists");
else
    NSLog(@"Does not exist");

打印:

Does not exist

【讨论】:

  • 现代 objc 怎么样?如果我使用 dict[@"key"] 它会崩溃
  • @OMGPOP 它对我有用。
  • 这对我不起作用。给出错误。
  • 添加了关于 'an NSDictionary cannot contain nil values' 的信息:如果你想要一个带有 'nothing' 作为值的键,只需放置对象 [NSNULL null]。
【解决方案2】:

Trojanfoe 可能更好,但您也可以这样做:

[[taglistDict allKeys]containsObject:key]

【讨论】:

    【解决方案3】:

    假设密钥的类型为 NSString 并且 keys 是字典,那么您应该改用以下内容:

    if [keys containObject:key] {
     // do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2017-12-26
      • 2013-04-07
      • 1970-01-01
      相关资源
      最近更新 更多