How to check if an NSDictionary or NSMutableDictionary contains a key?

前端 未结 16 2279
北海茫月
北海茫月 2020-11-28 00:52

I need to check if an dict has a key or not. How?

相关标签:
16条回答
  • 2020-11-28 01:24
    if ([MyDictionary objectForKey:MyKey]) {
          // "Key Exist"
    } 
    
    0 讨论(0)
  • 2020-11-28 01:29
    if ([mydict objectForKey:@"mykey"]) {
        // key exists.
    }
    else
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-28 01:31

    When using JSON dictionaries:

    #define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
    
    if( isNull( dict[@"my_key"] ) )
    {
        // do stuff
    }
    
    0 讨论(0)
  • 2020-11-28 01:35
    if ([[dictionary allKeys] containsObject:key]) {
        // contains key
    }
    

    or

    if ([dictionary objectForKey:key]) {
        // contains object
    }
    
    0 讨论(0)
  • 2020-11-28 01:35

    Because nil cannot be stored in Foundation data structures NSNull is sometimes to represent a nil. Because NSNull is a singleton object you can check to see if NSNull is the value stored in dictionary by using direct pointer comparison:

    if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
    
    0 讨论(0)
  • 2020-11-28 01:35

    I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:

    id obj = [dict objectForKey:@"blah"];
    
    if (obj) {
       // use obj
    } else {
       // Do something else
    }
    
    0 讨论(0)
提交回复
热议问题