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


当前回答

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

其他回答

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

这是针对嵌套的字典结构

当使用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");

是的。这类错误非常常见,会导致应用程序崩溃。所以我使用添加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"];

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