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


当前回答

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

其他回答

当使用JSON字典时:

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

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

我喜欢费尔南德斯的回答,尽管你问了两次obj。

这也应该(或多或少与马丁的A相同)。

id obj;

if ((obj=[dict objectForKey:@"blah"])) {
   // use obj
} else {
   // Do something else like creating the obj and add the kv pair to the dict
}

马丁的回答和这个答案都适用于iPad2 iOS 5.0.1 9A405

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

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

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

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

if (obj) {
   // use obj
} else {
   // Do something else
}