首页 文章

如何检查NSDictionary或NSMutableDictionary是否包含密钥?

提问于
浏览
450

我需要检查dict是否有密钥 . 怎么样?

15 回答

  • 162

    如果密钥不存在, objectForKey 将返回nil .

  • 8
    if ([[dictionary allKeys] containsObject:key]) {
        // contains key
    }
    

    要么

    if ([dictionary objectForKey:key]) {
        // contains object
    }
    
  • 5

    更新的Objective-C和Clang版本具有现代语法:

    if (myDictionary[myKey]) {
    
    }
    

    您不必检查与nil的相等性,因为只有非零的Objective-C对象可以存储在字典(或数组)中 . 并且所有Objective-C对象都是真实的值 . 甚至 @NO@0[NSNull null] 评估为真 .

    编辑:斯威夫特现在是一个东西 .

    对于Swift,你会尝试类似下面的内容

    if let value = myDictionary[myKey] {
    
    }
    

    如果myKey在dict中,则此语法仅执行if块,如果是,则将值存储在value变量中 . 请注意,这适用于0等虚假值 .

  • 4
    if ([mydict objectForKey:@"mykey"]) {
        // key exists.
    }
    else
    {
        // ...
    }
    
  • 3

    使用JSON词典时:

    #define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
    
    if( isNull( dict[@"my_key"] ) )
    {
        // do stuff
    }
    
  • 9

    我喜欢费尔南德斯的答案,即使你要求两次obj .

    这也应该做(或多或少与马丁的A相同) .

    id obj;
    
    if ((obj=[dict objectForKey:@"blah"])) {
       // use obj
    } else {
       // Do something else like creating the obj and add the kv pair to the dict
    }
    

    Martin和这个答案都适用于iPad2 iOS 5.0.1 9A405

  • 5

    一个非常讨厌的问题,只是浪费了我的一些时间调试 - 你可能会发现自己提示自动完成尝试使用 doesContain 似乎工作 .

    除外, doesContain 使用id比较而不是 objectForKey 使用的哈希比较,所以如果你有一个带字符串键的字典,它将返回NO给 doesContain .

    NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
    keysByName[@"fred"] = @1;
    NSString* test = @"fred";
    
    if ([keysByName objectForKey:test] != nil)
        NSLog(@"\nit works for key lookups");  // OK
    else
        NSLog(@"\nsod it");
    
    if (keysByName[test] != nil)
        NSLog(@"\nit works for key lookups using indexed syntax");  // OK
    else
        NSLog(@"\nsod it");
    
    if ([keysByName doesContain:@"fred"])
        NSLog(@"\n doesContain works literally");
    else
        NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain
    
  • 0

    是 . 这种错误很常见,导致应用程序崩溃 . 所以我用它在每个项目中添加NSDictionary,如下所示:

    //.h文件代码:

    @interface NSDictionary (AppDictionary)
    
    - (id)objectForKeyNotNull : (id)key;
    
    @end
    

    //.m文件代码如下

    #import "NSDictionary+WKDictionary.h"
    
    @implementation NSDictionary (WKDictionary)
    
     - (id)objectForKeyNotNull:(id)key {
    
        id object = [self objectForKey:key];
        if (object == [NSNull null])
         return nil;
    
        return object;
     }
    
    @end
    

    在代码中,您可以使用如下:

    NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
    
  • 1

    使用Swift,它将是:

    if myDic[KEY] != nil {
        // key exists
    }
    
  • 1

    用于检查NSDictionary中密钥的存在:

    if([dictionary objectForKey:@"Replace your key here"] != nil)
        NSLog(@"Key Exists");
    else
        NSLog(@"Key not Exists");
    
  • 97

    因为nil不能存储在Foundation数据结构中 NSNull 有时代表 nil . 因为 NSNull 是一个单例对象,您可以通过使用直接指针比较来检查 NSNull 是否是存储在字典中的值:

    if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
    
  • 3

    我建议你将查找结果存储在temp变量中,测试temp变量是否为nil然后使用它 . 这样你两次看起来不一样的对象:

    id obj = [dict objectForKey:@"blah"];
    
    if (obj) {
       // use obj
    } else {
       // Do something else
    }
    
  • 22

    正如Adirael建议 objectForKey 检查密钥存在但是当你在可空字典中调用 objectForKey 时,应用程序崩溃所以我从以下方式修复了这个问题 .

    - (instancetype)initWithDictionary:(NSDictionary*)dictionary {
    id object = dictionary;
    
    if (dictionary && (object != [NSNull null])) {
        self.name = [dictionary objectForKey:@"name"];
        self.age = [dictionary objectForKey:@"age"];
    }
    return self;
    

    }

  • 1

    Solution for swift 4.2

    因此,如果您只想回答字典是否包含密钥的问题,请询问:

    let keyExists = dict[key] != nil
    

    如果您想要该值并且您知道字典包含密钥,请说:

    let val = dict[key]!
    

    但是,如果通常发生,你不知道它包含密钥 - 你想获取它并使用它,但只有它存在 - 然后使用像 if let 这样的东西:

    if let val = dict[key] {
        // now val is not nil and the Optional has been unwrapped, so use it
    }
    
  • 755
    if ([MyDictionary objectForKey:MyKey]) {
          // "Key Exist"
    }
    

相关问题