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

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

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

16条回答
  •  再見小時候
    2020-11-28 01:47

    As Adirael suggested objectForKey to check key existance but When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from following way.

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

    }

提交回复
热议问题