NSDictionary中存在检查密钥


76

如何检查是否存在?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]

我想知道此密钥是否存在。我怎样才能做到这一点?

非常感谢你 :)

编辑:dataArray中有对象。这些对象是NSDictionaries。


为什么要使用-valueForKey:而不是-objectForKey:?前者用于键值编码,但比后者慢一些。

Answers:


158

我相信这[dataArray objectAtIndex:indexPathSet.row]是返回一个NSDictionary,在这种情况下,你可以简单地检查的结果,valueForKeynil.

例如:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // The key existed...

}
else {
    // No joy...

}

该键的值也可以为零,因此该方法将无法完全测试字典中是否存在键
Andrei

1
@AndreiA。您不能在NSDictionary中添加nil。
约翰·帕克

46

因此,我知道您已经选择了一个答案,但是我发现它作为上的一个类别非常有用NSDictionary。此时,您会通过所有这些不同的答案开始提高效率。h ... 6之1 ...

- (BOOL)containsKey: (NSString *)key {
     BOOL retVal = 0;
     NSArray *allKeys = [self allKeys];
     retVal = [allKeys containsObject:key];
     return retVal;
}

我在类别中也编写了相同的方法,但是使用UIImageWriteToSavedPhotosAlbum()时发生了奇怪的崩溃。缩小范围后,我从containsKey => hasKey更改了方法名称,崩溃消失了
kaala 2013年

这比公认的答案要好得多。我想按一个键而不是键的值为nil进行搜索。您可以在字典中有一个指向nil值的键。但是关键存在。接受的答案不涉及这种情况。但是这里的解决方案可以。
侯曼

3
@Hooman:关于值nil的键是不正确的:NSDictionary文档的第二段(developer.apple.com/library/mac/documentation/Cocoa/Reference/…)指出“键或值都不能为零;如果需要在字典中表示空值,则应使用NSNull。” 此答案和可接受的答案都适用于您的情况,即使用字典中某个键的值为null(NSNull类型)的字典。
Jarno Lamberg 2014年

1
或者:返回[[self allKeys] containsObject:key]吗?是:否;
smileBot

3
好的标注,@ Jamo。我会避开这个答案。我的猜测是,在幕后,对allKeys的调用和对containsObject的调用都至少为O(n),而valueForKey可能要少得多。
Orion elenzil 2014年

34

检查是否为零:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

该键的值也可以为nil,因此该方法将无法完全测试字典中是否存在键
Andrei

@AndreiA。nilNSDictionary中不能同时包含键和值。要表示nil,可以使用NSNull。
亚伦·阿什

9

这也可以通过以下语法在Objective-C文字中使用:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");

对于下面的快速版本,代码有效。let headers:Dictionary = httpResponse .allHeaderFields if(headers [“ errorcode”]!= nil){print(“错误码存在”)}
Narasimha Nallamsetty

0
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

那是正确的答案。


1
从BOOL到NSNull *的转换是什么?
NiñoScript

0

尝试这个:

if ([dict objectForKey:@"bla"]) {
   // use obj
} else {
   // Do something else like create the object
}

1
从技术上讲,这可能是正确的解释,但是如果您在答案正文中提供有关推理的更详细讨论,则可以为社区提供更好的服务(并且可能会获得更多支持)。为什么适合使用objectForKey:而不是其他方法?为什么不显式地必须检查值?至少,使用问题中提供的代码示例将使您的示例与原始问题更加容易。
Palpatim 2014年

0

此功能相同,但代码更少:

if (dataArray[indexPathSet.row][@"SetEntries"] != nil) { /* the key exists */        } 
else                                                   { /* the key doesn't exist */ }

0

检查字典包含任何值。我更喜欢[dic allKeys] .count> 0进行检查。


0

使用(unsigned long)选项:

if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
    // Key exist;
}else{
    // Key not exist;
};
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.