繁体   English   中英

检查密钥存在于NSDictionary中

[英]Check key exists in 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...

}

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

这个做的相同,但代码较少:

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

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

使用(unsigned long)选项:

if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
    // Key exist;
}else{
    // Key not exist;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM