我需要检查字典是否有钥匙。如何?


当前回答

如果键不存在,objectForKey将返回nil。

其他回答

当使用JSON字典时:

#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]

if( isNull( dict[@"my_key"] ) )
{
    // do stuff
}

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

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

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

}

if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 

如果键不存在,objectForKey将返回nil。

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