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


当前回答

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

这是针对嵌套的字典结构

其他回答

if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 

在NSDictionary中检查key是否存在:

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

当使用JSON字典时:

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

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

使用Swift,它将是:

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

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。