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


当前回答

正如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;

}

其他回答

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

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

在NSDictionary中检查key是否存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");
if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

使用Swift,它将是:

if myDic[KEY] != nil {
    // key exists
}