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


当前回答

if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

这是针对嵌套的字典结构

其他回答

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

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

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

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

使用Swift,它将是:

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

一个非常严重的问题,浪费了我调试的时间-你可能会发现自动完成提示你尝试使用doesContain,这似乎是有效的。

除此之外,doesContain使用id比较而不是objectForKey使用的散列比较,所以如果你有一个字符串键的字典,它将返回NO给doesContain。

NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";

if ([keysByName objectForKey:test] != nil)
    NSLog(@"\nit works for key lookups");  // OK
else
    NSLog(@"\nsod it");

if (keysByName[test] != nil)
    NSLog(@"\nit works for key lookups using indexed syntax");  // OK
else
    NSLog(@"\nsod it");

if ([keysByName doesContain:@"fred"])
    NSLog(@"\n doesContain works literally");
else
    NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

这是针对嵌套的字典结构