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


当前回答

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

其他回答

在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
}

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

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

swift 4.2解决方案

所以,如果你只想回答这个问题,字典是否包含键,问:

let keyExists = dict[key] != nil

如果你想要这个值,并且你知道字典中包含这个键,那么说:

let val = dict[key]!

但如果,就像通常发生的那样,你不知道它包含键-你想获取它并使用它,但前提是它存在-然后使用类似if let的东西:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}