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

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

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

16条回答
  •  被撕碎了的回忆
    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"];
    

提交回复
热议问题