ios 检查密钥存在于 NSDictionary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4635106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check key exists in NSDictionary
提问by cocos2dbeginner
how can I check if this exists?:
我如何检查这是否存在?:
[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]
I want to know whether this key exists or not. How can I do that?
我想知道这个键是否存在。我怎样才能做到这一点?
Thank you very much :)
非常感谢 :)
EDIT: dataArray has Objects in it. And these objects are NSDictionaries.
编辑:dataArray 中有对象。这些对象是 NSDictionaries。
回答by John Parker
I presume that [dataArray objectAtIndex:indexPathSet.row]
is returning an NSDictionary
, in which case you can simply check the result of valueForKey
against nil.
我相信这[dataArray objectAtIndex:indexPathSet.row]
是返回一个NSDictionary
,在这种情况下,你可以简单地检查的结果,valueForKey
对nil.
For example:
例如:
if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
// The key existed...
}
else {
// No joy...
}
回答by Miles Alden
So I know you already selected an answer, but I found this to be rather useful as a category on NSDictionary
. You start getting into efficiency at this point with all these different answers. Meh...6 of 1...
所以我知道您已经选择了一个答案,但我发现它作为NSDictionary
. 在这一点上,您开始通过所有这些不同的答案来提高效率。嗯...6 的 1...
- (BOOL)containsKey: (NSString *)key {
BOOL retVal = 0;
NSArray *allKeys = [self allKeys];
retVal = [allKeys containsObject:key];
return retVal;
}
回答by BoltClock
Check if it's nil:
检查它是否为零:
if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
// SetEntries exists in this dict
} else {
// No SetEntries in this dict
}
回答by Yogesh Kumar
this also works using Objective-C literals using the following syntax:
这也适用于使用以下语法的 Objective-C 文字:
NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");
回答by zedzhao
Check dictionary contains any value. I prefer [dic allKeys].count > 0 to check.
检查字典包含任何值。我更喜欢 [dic allKeys].count > 0 来检查。
回答by TheAlphaGhost
Use the (unsigned long)
option:
使用(unsigned long)
选项:
if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
// Key exist;
}else{
// Key not exist;
};
回答by WalterDa
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
// SetEntries exists in this dict
} else {
// No SetEntries in this dict
}
That's the right answer.
这就是正确的答案。
回答by Tea
Try this:
尝试这个:
if ([dict objectForKey:@"bla"]) {
// use obj
} else {
// Do something else like create the object
}
回答by Jesus
This one does the same but with less code:
这个功能相同,但代码更少:
if (dataArray[indexPathSet.row][@"SetEntries"] != nil) { /* the key exists */ }
else { /* the key doesn't exist */ }