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


当前回答

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

其他回答

是的。这类错误非常常见,会导致应用程序崩溃。所以我使用添加NSDictionary在每个项目如下:

//.h文件代码:

@interface NSDictionary (AppDictionary)

- (id)objectForKeyNotNull : (id)key;

@end

/ /。M文件代码如下

#import "NSDictionary+WKDictionary.h"

@implementation NSDictionary (WKDictionary)

 - (id)objectForKeyNotNull:(id)key {

    id object = [self objectForKey:key];
    if (object == [NSNull null])
     return nil;

    return object;
 }

@end

在代码中,您可以使用如下:

NSStrting *testString = [dict objectForKeyNotNull:@"blah"];

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

当使用JSON字典时:

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

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

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

使用Swift,它将是:

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