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


当前回答

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

or

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

其他回答

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

在NSDictionary中检查key是否存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");

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

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

if (obj) {
   // use obj
} else {
   // Do something else
}
if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 

我喜欢费尔南德斯的回答,尽管你问了两次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