如何检查NSDictionary或NSMutableDictionary是否包含密钥?

问题描述 投票:451回答:15

我需要检查dict是否有密钥。怎么样?

objective-c foundation
15个回答
760
投票

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


3
投票

用于检查NSDictionary中密钥的存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");

3
投票

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

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

2
投票

快速解决方案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
}

1
投票

我建议你将查找结果存储在temp变量中,测试temp变量是否为nil然后使用它。这样你两次看起来不一样的对象:

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

if (obj) {
   // use obj
} else {
   // Do something else
}

1
投票

正如Adirael建议qazxsw poi检查密钥存在但是当你调用qazxsw poi nullable字典时,应用程序会崩溃所以我从以下方式修复了这个问题。

objectForKey

}


0
投票
objectForKey

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

要么

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

98
投票

更新的Objective-C和Clang版本具有现代语法:

if (myDictionary[myKey]) {

}

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

编辑:斯威夫特现在是一个东西。

对于Swift,你会尝试类似下面的内容

if let value = myDictionary[myKey] {

}

如果myKey在dict中,则此语法仅执行if块,如果是,则将值存储在value变量中。请注意,这适用于0等虚假值。


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

9
投票

使用JSON词典时:

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

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

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
}

Martin和这个答案都适用于iPad2 iOS 5.0.1 9A405


5
投票

一个非常讨厌的陷阱,只是浪费了我的一些时间调试 - 你可能会发现自己完成自动完成尝试使用doesContain似乎工作。

除此之外,doesContain使用id比较而不是objectForKey使用的哈希比较,所以如果你有一个带字符串键的字典,它将返回NO给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

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"];

4
投票

使用Swift,它将是:

if myDic[KEY] != nil {
    // key exists
}
© www.soinside.com 2019 - 2024. All rights reserved.