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


当前回答

在NSDictionary中检查key是否存在:

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

其他回答

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

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

因为nil不能存储在Foundation数据结构中,NSNull有时表示nil。因为NSNull是一个单例对象,你可以通过直接指针比较来检查NSNull是否是存储在字典中的值:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

当使用JSON字典时:

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

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

在NSDictionary中检查key是否存在:

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