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


当前回答

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

}

其他回答

我建议您将查找结果存储在一个临时变量中,测试临时变量是否为nil,然后使用它。这样你就不会重复查找同一个对象:

id obj = [dict objectForKey:@"blah"];

if (obj) {
   // use obj
} else {
   // Do something else
}
if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

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

正如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"
}