检查密钥存在于NSDictionary中

coc*_*ner 75 iphone objective-c nsdictionary ios

我如何检查是否存在?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你 :)

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

Joh*_*ker 157

我认为这[dataArray objectAtIndex:indexPathSet.row]是返回一个NSDictionary,在这种情况下你可以简单地检查valueForKey反对的结果nil.

例如:

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

}
else {
    // No joy...

}
Run Code Online (Sandbox Code Playgroud)


Mil*_*den 46

所以我知道你已经选择了答案,但我发现这个作为一个类别非常有用NSDictionary.在这一点上,您开始通过所有这些不同的答案开始提高效率.嗯... 6 of 1 ...

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

  • @Hooman:关于值为nil的密钥不正确:NSDictionary文档的第二段(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/ Reference.html)声明"键和值都不能为零;如果需要在字典中表示空值,则应使用NSNull." 这个和接受的答案都适用于您的场景,即使用字典,其中某个键的值为null(类型为NSNull). (3认同)
  • 好的标注,@ Jao.我会避开这个答案.我的猜测是,在all cover下,对allKeys的调用和对containsObject的调用都至少为O(n),而valueForKey可能要小得多. (3认同)

Bol*_*ock 34

检查它是否为零:

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


Yog*_*mar 8

这也可以使用以下语法使用Objective-C文字:

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