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


当前回答

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

其他回答

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

or

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

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

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

这是针对嵌套的字典结构

使用Swift,它将是:

if myDic[KEY] != nil {
    // key 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"];