检查密钥存在于NSDictionary

我该如何检查是否存在?

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

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

非常感谢你 :)

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

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

例如:

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

所以我知道你已经select了一个答案,但我发现这是相当有用的NSDictionary类别。 在这一点上,你开始进入效率的所有这些不同的答案。 呃… 6之1 …

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

检查是否为零:

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

这也使用Objective-C字面值使用以下语法:

 NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" }; if (dict[@"key2"]) NSLog(@"Exists"); else NSLog(@"Does not exist"); 
 if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) { // SetEntries exists in this dict } else { // No SetEntries in this dict } 

这是正确的答案。

尝试这个:

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

这一个是相同的,但代码less:

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

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