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

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

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

相关标签:
16条回答
  • 2020-11-28 01:35
    if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
       //do something if doesn't exist
    }
    

    This is for nested dictionary structure

    0 讨论(0)
  • 2020-11-28 01:36

    Using Swift, it would be:

    if myDic[KEY] != nil {
        // key exists
    }
    
    0 讨论(0)
  • 2020-11-28 01:37

    objectForKey will return nil if a key doesn't exist.

    0 讨论(0)
  • 2020-11-28 01:37

    For checking existence of key in NSDictionary:

    if([dictionary objectForKey:@"Replace your key here"] != nil)
        NSLog(@"Key Exists");
    else
        NSLog(@"Key not Exists");
    
    0 讨论(0)
  • 2020-11-28 01:42

    I like Fernandes' answer even though you ask for the obj twice.

    This should also do (more or less the same as Martin's 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's and this answer both work on iPad2 iOS 5.0.1 9A405

    0 讨论(0)
  • 2020-11-28 01:43

    Yes. This kind of errors are very common and lead to app crash. So I use to add NSDictionary in each project as below:

    //.h file code :

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

    //.m file code is as below

    #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
    

    In code you can use as below:

    NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
    
    0 讨论(0)
提交回复
热议问题