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


当前回答

Objective-C和Clang的最新版本对此有了现代语法:

if (myDictionary[myKey]) {

}

你不需要检查是否与nil相等,因为只有非nil的Objective-C对象可以存储在字典(或数组)中。所有Objective-C对象都是真值。即使@NO, @0,和[NSNull null]计算为真。

编辑:霉霉现在很火。

对于Swift,您可以尝试以下内容

if let value = myDictionary[myKey] {

}

此语法只在myKey在dict中时执行if块,如果在则值存储在value变量中。请注意,这甚至适用于假值,如0。

其他回答

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

一个非常严重的问题,浪费了我调试的时间-你可能会发现自动完成提示你尝试使用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 ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}
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
}