462

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

4

16 回答 16

775

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

于 2010-05-06T21:30:04.270 回答
163
if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

或者

if ([dictionary objectForKey:key]) {
    // contains object
}
于 2010-05-06T21:31:43.607 回答
99

最新版本的 Objective-C 和 Clang 有一个现代语法:

if (myDictionary[myKey]) {

}

您不必检查与 nil 是否相等,因为只有非 nil Objective-C 对象可以存储在字典(或数组)中。并且所有 Objective-C 对象都是真值。甚至@NO, @0, 和[NSNull null]评估为真。

编辑:斯威夫特现在是一件事。

对于 Swift,您可以尝试以下操作

if let value = myDictionary[myKey] {

}

如果 myKey 在 dict 中,则此语法只会执行 if 块,如果是,则值存储在 value 变量中。请注意,这甚至适用于像 0 这样的虚假值。

于 2014-02-25T00:09:28.130 回答
22
if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}
于 2010-05-06T21:30:27.200 回答
9

使用 JSON 字典时:

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

if( isNull( dict[@"my_key"] ) )
{
    // do stuff
}
于 2015-07-24T14:40:17.673 回答
8

我喜欢费尔南德斯的回答,即使您两次要求 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

于 2012-02-06T20:07:20.643 回答
5

是的。这种错误很常见,会导致应用程序崩溃。所以我使用在每个项目中添加 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"];
于 2013-10-03T04:50:39.197 回答
5

一个非常讨厌的问题,只是浪费了我的一点调试时间——你可能会发现自动完成提示自己尝试使用doesContain似乎可行的方法。

除了,doesContain使用 id 比较而不是使用的哈希比较,objectForKey因此如果您有一个带有字符串键的字典,它将返回 NO 到 a doesContain

NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";

if ([keysByName objectForKey:test] != nil)
    NSLog(@"\nit works for key lookups");  // OK
else
    NSLog(@"\nsod it");

if (keysByName[test] != nil)
    NSLog(@"\nit works for key lookups using indexed syntax");  // OK
else
    NSLog(@"\nsod it");

if ([keysByName doesContain:@"fred"])
    NSLog(@"\n doesContain works literally");
else
    NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain
于 2013-11-10T20:11:02.267 回答
5

使用 Swift,它将是:

if myDic[KEY] != nil {
    // key exists
}
于 2014-10-28T07:33:57.707 回答
4

检查 NSDictionary 中是否存在键:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");
于 2016-01-11T05:36:59.187 回答
3

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

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
于 2011-07-07T22:07:15.367 回答
2

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
}
于 2019-02-13T16:49:16.397 回答
1

我建议您将查找结果存储在临时变量中,测试临时变量是否为 nil,然后使用它。这样你就不会两次看同一个对象:

id obj = [dict objectForKey:@"blah"];

if (obj) {
   // use obj
} else {
   // Do something else
}
于 2011-06-25T21:51:40.907 回答
1
if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 
于 2017-04-19T07:08:24.573 回答
1

正如 Adirael 建议objectForKey检查密钥是否存在,但是当您调用objectForKey可空字典时,应用程序崩溃了,所以我通过以下方式修复了这个问题。

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

if (dictionary && (object != [NSNull null])) {
    self.name = [dictionary objectForKey:@"name"];
    self.age = [dictionary objectForKey:@"age"];
}
return self;

}

于 2018-08-10T07:37:17.227 回答
0
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

这是用于嵌套字典结构

于 2020-11-16T11:29:10.087 回答